1. 程式人生 > 其它 >PHP通過CURL獲取遠端檔案header頭資訊

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'])

本方法可以不下載檔案,直接獲取檔案大小

文章乃參考、轉載其他部落格所得,僅供自己學習作筆記使用!!!