file_get_contents when url doesn't exist

前端 未结 8 2243
刺人心
刺人心 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:04

    While file_get_contents is very terse and convenient, I tend to favour the Curl library for better control. Here's an example.

    function fetchUrl($uri) {
        $handle = curl_init();
    
        curl_setopt($handle, CURLOPT_URL, $uri);
        curl_setopt($handle, CURLOPT_POST, false);
        curl_setopt($handle, CURLOPT_BINARYTRANSFER, false);
        curl_setopt($handle, CURLOPT_HEADER, true);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 10);
    
        $response = curl_exec($handle);
        $hlength  = curl_getinfo($handle, CURLINFO_HEADER_SIZE);
        $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
        $body     = substr($response, $hlength);
    
        // If HTTP response is not 200, throw exception
        if ($httpCode != 200) {
            throw new Exception($httpCode);
        }
    
        return $body;
    }
    
    $url = 'http://some.host.com/path/to/doc';
    
    try {
        $response = fetchUrl($url);
    } catch (Exception $e) {
        error_log('Fetch URL failed: ' . $e->getMessage() . ' for ' . $url);
    }
    

提交回复
热议问题