通过PHP中的CURL获取图像大小

时间:2013-06-04 01:49:59

标签: php curl

我正在使用此代码在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;

3 个答案:

答案 0 :(得分: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是获取图片大小的正确方法,因为我在curlget_header

之间得到了不同的结果

答案 1 :(得分:0)

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

答案 2 :(得分: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";