5

我正在使用此代码在 php 中获取图像大小,它对我来说非常完美。

$img = get_headers("http://ultoo.com/img_single.php", 1);
$size = $img["Content-Length"];
echo $size;

但是如何通过 CURL 获得这个?我试过这个但不起作用。

$url = 'http://ultoo.com/img_single.php';
$ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_HEADER, 1);
 curl_setopt($ch, CURLOPT_HTTPHEADER, "Content-Length" );
 //curl_setopt($ch, CURLOPT_NOBODY, 1);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 $result = curl_exec($ch);

 $filesize = $result["Content-Length"];

  curl_close($ch);

  echo $filesize;
4

3 回答 3

1

设置curl_setopt($ch, CURLOPT_HTTPHEADER, true );,然后print_r($result),你会看到类似

HTTP/1.1 200 OK
Date: Tue, 04 Jun 2013 03:12:38 GMT
Server: Apache/2.2.15 (Red Hat)
X-Powered-By: PHP/5.3.3
Set-Cookie: PHPSESSID=rtd17m2uig3liu63ftlobcf195; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 211
Content-Type: image/png

我认为这不是Content-Length获取图像大小的正确方法,因为我在curl和之间得到不同的结果get_header

于 2013-06-04T03:21:44.983 回答
0

也许这对你有用(假设页面总是只返回一个img/png) - 我包含一个“写入文件”只是为了能够比较屏幕输出与文件大小(png来自页面):

$url = 'http://ultoo.com/img_single.php'; 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //return the output as a variable
curl_setopt($ch, CURLOPT_TIMEOUT, 10); //time out length
$data = curl_exec($ch);
if (!$data) {
    echo "<br />cURL error:<br/>\n";
    echo "#" . curl_errno($ch) . "<br/>\n";
    echo curl_error($ch) . "<br/>\n";
    echo "Detailed information:";
    var_dump(curl_getinfo($ch));
    die();
}
curl_close($ch);
$handle = fopen("image.png", "w");
fwrite($handle, $data);
fclose($handle);
$fileSize = strlen($data);
echo "fileSize = $fileSize\n";
于 2013-06-04T04:48:19.403 回答
0

我之前遇到过这个问题,我使用的脚本可以在这里找到 -> http://boolean.co.nz/blog/curl-remote-filesize/638/。与上面的帖子非常相似,但更直截了当,更不宽容。

于 2013-06-04T02:12:31.817 回答