file_get_contents when url doesn't exist

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

    Simple and functional (easy to use anywhere):

    function file_contents_exist($url, $response_code = 200)
    {
        $headers = get_headers($url);
    
        if (substr($headers[0], 9, 3) == $response_code)
        {
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }
    

    Example:

    $file_path = 'http://www.google.com';
    
    if(file_contents_exist($file_path))
    {
        $file = file_get_contents($file_path);
    }
    
    0 讨论(0)
  • 2020-12-01 03:19
    $url = 'https://www.yourdomain.com';
    

    Normal

    function checkOnline($url) {
        $headers = get_headers($url);
        $code = substr($headers[0], 9, 3);
        if ($code == 200) {
            return true;
        }
        return false;
    }
    
    if (checkOnline($url)) {
        // URL is online, do something..
        $getURL = file_get_contents($url);     
    } else {
        // URL is offline, throw an error..
    }
    

    Pro

    if (substr(get_headers($url)[0], 9, 3) == 200) {
        // URL is online, do something..
    }
    

    Wtf level

    (substr(get_headers($url)[0], 9, 3) == 200) ? echo 'Online' : echo 'Offline';
    
    0 讨论(0)
提交回复
热议问题