php教程

file_get_contents函数判断链接是否失效

php教程 51源码 2023-03-08 人阅读

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

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

file_get_contents代码如下:

function getUrl($url) {
    $content = file_get_contents($url);
    return array(
            'headers' => $http_response_header,
            'content' => $content
        );
}
$response = getUrl('https://www.51yma.cn/');
if ($response['content'] === false)
    echo $response['headers'][0];   // HTTP/1.1 401 Unauthorized
else
    echo $response['content'];

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

<?php
function get_contents() {
  file_get_contents("https://www.51yma.cn/");
  return $http_response_header;
}
var_dump(get_contents());
?>

响应如下:

array(12) {
    [0] => string(15) "HTTP/1.1 200 OK"
    [1] => string(35) "Date: Tue, 13 Aug 2019 05:39:50 GMT"
    [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"

版权声明:文章搜集于网络,如有侵权请联系本站,转载请说明出处:https://www.51yma.cn/jiaocheng/php/1105.html
文章来源:
标签 PHP函数 PHP判断