file_get_contents函数判断链接是否失效

在nginx环境中不能使用get_headers函数时,可以借助PHP的file_get_contents函数来获取HTTP响应头判断链接是否有效。通过检查HTTP状态码,例如HTTP/1.1200OK表示链接正常,否则可能已失效。示例代码展示了如何实现这一功能并返回HTTP头信息和内容。
摘要由CSDN通过智能技术生成

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

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

file_get_contents代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

function getUrl($url) {

    $content file_get_contents($url);

    return array(

            'headers' => $http_response_header,

            'content' => $content

        );

}

$response = getUrl('https://www.wdzzz.com/');

if ($response['content'] === false)

    echo $response['headers'][0];   // HTTP/1.1 401 Unauthorized

else

    echo $response['content'];

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

1

2

3

4

5

6

7

<?php

function get_contents() {

  file_get_contents("https://www.wdzzz.com/");

  return $http_response_header;

}

var_dump(get_contents());

?>

响应如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

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"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

执刀人的工具库

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值