8

How can I detect this error using php curl? curl return success even if the URL does not exist.

Not Found
The requested URL /foo/index.php/items/edit was not found on this server.

My code

$post_fields = array('info' => json_encode($fields));
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_POST,count($post_fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$post_fields);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLINFO_CONTENT_TYPE,'application/x-www-form-urlencoded charset=utf-8');

    $result = curl_exec($ch);
    echo $result;

    if(curl_error($ch)){
        $result = curl_error($ch);
        curl_close($ch);
        return $result;
    }else{
        curl_close($ch);
        return json_decode($result,true);

    }
2
  • 4
    $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); check it if it is 404 or something else Commented May 20, 2013 at 4:41
  • url not found should return a 404 error, so you should check on the headers of the response.
    – MatRt
    Commented May 20, 2013 at 4:41

1 Answer 1

11

use this to get HTTP status code:

$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

If 404, it means the request URL cannot be found.

Note: remember to issue this line before curl_close($ch);

2
  • its working thanks..but Can I assuem that all status codes other than 200 is a failure? Commented May 20, 2013 at 4:55
  • 1
    Yes, but you should look into what server responses to you too. 200 only means the request is successful.
    – Raptor
    Commented May 20, 2013 at 5:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.