简体   繁体   中英

curl returns 200 for page not found

$ch = curl_init();    
$varpost = '&res=1';  // Initiate cURL
$url = 'http://www.testxcvt.com/';// is 404 page
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);  
curl_setopt($ch, CURLOPT_POSTFIELDS, $varpost);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec ($ch); // Execute
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if(curl_errno($ch))
    {
        echo 'error:' . curl_error($ch);
    }
curl_close ($ch); // Close cURL handle 

PFA the code that i have. i get 200 when i display $code. in my browser i get an advertisement for 404 pages. i am not sure what is the reson to get 200 for 404 page.

Please help

Where are you executing the code from?

When I try it locally, I get:

error:Could not resolve host: www.testxcvt.com

And $code comes back as 0 .

If you try another URL, like http://www.text.com - does it work?

If you try this code below you will see that curl makes post to google and google responds with 405 error so 404 check is false. Then page output is checked for 403 in it and handled.

In your case page doesn't return 405 http code but 200 so you should check page output and set correct error message to find.
Only problem is if that error message occurs somewhere on pages you actually need, then you won't get them also.

<?php
$ch = curl_init();    
$varpost = '&res=1';  // Initiate cURL
$url = 'http://www.google.com/';// is 404 page
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);  
curl_setopt($ch, CURLOPT_POSTFIELDS, $varpost);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec ($ch); // Execute
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($code == 404){
    /* handle real 404 here. */
    echo 'real 404 found';
}else{
    // here you can set your own error, for example 'Page Not Found (12)'
    if (strpos($output, '405') !== false) {
        // 404 page found
        echo 'Google custom error 405 found';
        print_r($output);
    }else{
        // no 404 error
        echo 'Google custom error not found';
        print_r($output);
    }
}
curl_close ($ch); // Close cURL handle 
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM