使用PHP计算远程图像文件大小


Calculate Remote Image File Size Using PHP

如何在远程服务器上查找图像的文件大小?在本地机器上,我可以使用filesize(),但我想在不下载图像的情况下找到大小

// Similar solution seen in another stackoverflow post:
// By default get_headers uses a GET request to fetch the headers. If you
// want to send a HEAD request instead, you can do so using a stream context:
stream_context_set_default(
    array(
        'http' => array(
            'method' => 'HEAD'
        )
    )
);
$headers = get_headers($source_file,1);
$source_file_size = null;
if (is_array($headers) && array_key_exists('Content-Length',$headers)) {
    $source_file_size = intval($headers['Content-Length']);
}
if ($source_file_size === null){ //we didn't get a Content-Length header
    /** Grab file to local disk and use filesize() to set $size **/
}
stream_context_set_default(
    array(
        'http' => array(
            'method' => 'GET'
        )
    )
);