生活的道路一旦选定,就要勇敢地走到底,决不回头。

发掘积累过程的快感

首页 » BIBLE模型 » PHP » php使用get_headers函数判断远程文件是否存在

php使用get_headers函数判断远程文件是否存在


get_headers(string $url, bool $associative = false, ?resource $context = null): array|false

get_headers() 返回一个数组,包含有服务器响应一个 HTTP 请求所发送的标头。

接下来请看 DEMO

    /**
     * 使用header信息判断远程服务器的某个文件是否存在
     * @param     $url
     * @param int $timeout
     * @return false
     */
    public static function fileExistsOnRemote($url,$timeout=5){
        $headerInfos=@get_headers($url,false,stream_context_create([
            'http'=>[
                'timeout'=>$timeout,
                'method'=>'HEAD',
            ]
        ]));
        if (!$headerInfos || !isset($headerInfos[0])){
            return false;
        }
        $regex='/HTTP\/\d(?:\.\d)?\s+(\d+)/';
        if (!preg_match($regex,$headerInfos[0],$matchs)){
            return false;
        }
        $httpCode=intval($matchs[1]);
        return $httpCode>=200 && $httpCode<300;
    }

使用 stream_context_create 创建一个上下文,并设置请求方式为 HEAD,设置一个请求超时。

互联网信息太多太杂,各互联网公司不断推送娱乐花边新闻,SNS,微博不断转移我们的注意力。但是,我们的时间和精力却是有限的。这里是互联网浩瀚的海洋中的一座宁静与美丽的小岛,供开发者歇息与静心潜心修炼。 “Bible”是圣经,有权威的书,我们的本意就是为开发者提供真正有用的的资料。 我的电子邮件 1217179982@qq.com,您在开发过程中遇到任何问题,欢迎与我联系。
Copyright © 2024. All rights reserved. 本站由 Helay 纯手工打造. 蜀ICP备15017444号