file_get_contents when url doesn't exist

前端 未结 8 2273
刺人心
刺人心 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: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';
    

提交回复
热议问题