PHP判断远程图片或文件或url是否存在-180

发布时间:2020-08-01 07:32:12 作者:DaddysGirl
来源:网络 阅读:5644

我通常使用curl判断判断远程图片或文件是否存在:

    /**
     * @link http://www.phpddt.com
     */
    function url_exists($url) {
        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        //不下载
        curl_setopt($ch, CURLOPT_NOBODY, 1);
        //设置超时
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
        if($http_code == 200) {
            return true;
        }
        return false;
    }


当然也有很多其它方法,或多或少有些限制和缺陷,如:
(1)使用fopen()函数,它要在allow_url_open开启的状态下,否则会报错。

    $url = 'https://cache.yisu.com/upload/information/20200310/52/108014.jpg';
    if(@fopen($url, 'r')) {
        echo '文件存在';
    } else {
        echo '文件不存在';
    }


(2)get_headers取得服务器响应一个 HTTP 请求所发送的所有标头,效率较低,你可以测试下。

    $url = 'https://cache.yisu.com/upload/information/20200310/52/108014.jpg';
     
    stream_context_set_default(
        array(
            'http' => array(
                 'timeout' => 1,
                )
        )
    );
     
    $headers = get_headers($url);
     
    if(preg_match('/200/',$headers[0])) {
        echo '文件存在';
    } else {
        echo '文件不存在';
    }


(3)file_get_contents()函数

     $opts = array(
        'http'=>array(
        'timeout'=>3,
        )
    );
    $context = stream_context_create($opts);
    $resource = @file_get_contents('https://cache.yisu.com/upload/information/20200310/52/108014.jpg', false, $context);
     
    if($resource) {
        echo '文件存在';
    } else {
        echo '文件不存在';
    }

推荐阅读:
  1. php判断远程资源是否存在
  2. php中如何判断文件或者目录是否存在

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

图片 18 是否存在

上一篇:ARP内网中截获目标主机图片

下一篇:Oracle 自动诊断信息库(Automatic Diagnostic Repository,ADR)

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》