PHP通過CURL獲取遠程文件header頭信息


使用CURL方法獲取遠程文件header頭信息,與內置函數get_headers不同的是,這個方法不用完整下載文件,只是下載頭部信息,速度理論會快一些。

public function getRemoteFileHeaders($url)
    {
    $options = array(
        CURLOPT_HEADER => true,
        CURLOPT_NOBODY => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_AUTOREFERER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTPHEADER => array('Accept: */*', 'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)', 'Connection: Keep-Alive')
    );
    $ch = curl_init($url);
    curl_setopt_array($ch, $options);
    $header = curl_exec($ch);
    $ret = curl_errno($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if ($ret === 0) {
        $head = array();
        $headArray = explode("\r\n", trim($header));
        $first = array_shift($headArray);
        preg_match("#HTTP/[0-9\.]+\s+([0-9]+)#", $first, $code);
        $head['code'] = intval($code[1]);
        foreach ($headArray as $v) {
        $arr = explode(':', $v, 2);
        $head[trim($arr[0])] = trim($arr[1]);
        }
        return $head;
    } else {
        return $error;
    }
}

 

Python request urllib 獲取遠程文件大小

Python request urllib 獲取遠程文件大小
有兩個方法都可以獲取文件大小
第一種使用requests庫

import urllib
import requests

url=r'https://down.qq.com/qqweb/PCQQ/PCQQ_EXE/PCQQ2020.exe'

download=requests.get(url)
print(download.headers['content-length'])

 


這個方法可以取到文件大小,但是缺點在於,首先會下載文件.

第二種使用urllib庫

import urllib
import requests

url=r'https://down.qq.com/qqweb/PCQQ/PCQQ_EXE/PCQQ2020.exe'

download=urllib.request.urlopen(url)
print(download.headers['content-length'])

本方法可以不下載文件,直接獲取文件大小


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM