PHP判斷遠程圖片或檔案或url是否存在-180

來源:互聯網
上載者:User

標籤:圖片

我通常使用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 = ‘http://www.phpddt.com/img/qrcode_for_phpddt.JPG‘;
    if(@fopen($url, ‘r‘)) {
        echo ‘檔案存在‘;
    } else {
        echo ‘檔案不存在‘;
    }


(2)get_headers取得伺服器響應一個 HTTP 要求所發送的所有標題,效率較低,你可以測試下。

    $url = ‘http://www.phpddt.com/img/qrcode_for_phpddt.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(‘http://www.phpddt.com/img/qrcode_for_phpddt.JPG‘, false, $context);
     
    if($resource) {
        echo ‘檔案存在‘;
    } else {
        echo ‘檔案不存在‘;
    }

本文出自 “yanzi” 部落格,請務必保留此出處http://daddysgirl.blog.51cto.com/1598612/1887742

PHP判斷遠程圖片或檔案或url是否存在-180

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.