菜鸡源码,专注精品下载!
当前位置:首页 > 建站教程 > 建站知识

使用file_get_contents函数判断链接是否失效

发布时间:2024-01-05  栏目:建站知识   浏览:   分类:php教程 PHP函数 PHP判断

`file_get_contents`函数是PHP中的一个内置函数,用于将整个文件读入一个字符串。它不能直接用于判断链接是否失效。但是,你可以通过尝试使用`file_get_contents`函数获取链接的内容,然后检查返回的HTTP状态码来判断链接是否失效。如果返回的状态码为404,那么链接可能已经失效。例如: ```php $url = "https://www.example.com"; $content = file_get_contents($url); if ($http_response_code == 404) { echo "链接已失效"; } else { echo "链接有效"; } ```

在nginx环境中无法使用get_headers函数方法,所以菜鸡源码这次分享的是用php的file_get_contents函数来判断链接是否失效。

原理就是通过file_get_contents函数远程访问链接,判断返回的$http_response_header的HTTP 标头。

file_get_contents代码如下:

functiongetUrl($url){$content=file_get_contents($url);returnarray('headers'=>$http_response_header,'content'=>$content);}$response=getUrl('https://www.caijicaiji.com/');if($response['content']===false)echo$response['headers'][0];//HTTP/1.1401Unauthorizedelseecho$response['content'];

不加判断,以数组的形式返回数据就是这样的。

<?phpfunctionget_contents(){file_get_contents("https://www.caijicaiji.com/");return$http_response_header;}var_dump(get_contents());?>

响应如下:

array(12){[0]=>string(15)"HTTP/1.1200OK"[1]=>string(35)"Date:Tue,13Aug201905:39:50GMT"[2]=>string(38)"Content-Type:text/html;charset=UTF-8"[3]=>string(17)"Connection:close"[4]=>string(21)"Vary:Accept-Encoding"[5]=>string(46)"X-Pingback:https://vircloud.net/action/xmlrpc"[6]=>string(70)"Set-Cookie:1ace4129ed475fea40c32ab2c48ab0c2_armxmod_online=U1;path=/"[7]=>string(14)"Server:vcloud"[8]=>string(71)"Strict-Transport-Security:max-age=15552000;includeSubdomains;preload"[9]=>string(31)"X-Xss-Protection:1;mode=block"[10]=>string(31)"X-Content-Type-Options:nosniff"[11]=>string(27)"X-Frame-Options:SAMEORIGIN"
评论
建站知识
建站知识
使用技巧
调试安装
运营推广