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

时间:2011-11-16 14:52:26

标签: php

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

1 个答案:

答案 0 :(得分:3)

// 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'
        )
    )
);