file_get_contents when url doesn't exist

前端 未结 8 2269
刺人心
刺人心 2020-12-01 02:37

I\'m using file_get_contents() to access a URL.

file_get_contents(\'http://somenotrealurl.com/notrealpage\');

If the URL is not real, it r

8条回答
  •  长情又很酷
    2020-12-01 03:02

    To avoid double requests as commented by Orbling on the answer of ynh you could combine their answers. If you get a valid response in the first place, use that. If not find out what the problem was (if needed).

    $urlToGet = 'http://somenotrealurl.com/notrealpage';
    $pageDocument = @file_get_contents($urlToGet);
    if ($pageDocument === false) {
         $headers = get_headers($urlToGet);
         $responseCode = substr($headers[0], 9, 3);
         // Handle errors based on response code
         if ($responseCode == '404') {
             //do something, page is missing
         }
         // Etc.
    } else {
         // Use $pageDocument, echo or whatever you are doing
    }
    

提交回复
热议问题