带CURL的PHP​​获取动态显示图像

时间:2014-10-07 11:52:19

标签: php curl

我正在使用以下代码在数据库中查询最多25个缩略图的图像值。我依靠CURL返回200代码以确定图像是否存在。如果不是,我想结束缩略图。

我的问题是,如果找不到全部25张图像,它会获取图像但会留下空白缩略图。我想不要形成

<?
$image = "<div class='wrap_img_small'><br>";
$ListingRid = $row['matrix_unique_id'];
$img_cnt = 1;
for ($c=1;$c<25;$c++) {
    $c_ext = $c;
    $ch = curl_init("http://www.domain.com/feeds/fort/rets_images/{$ListingRid}_{$c_ext}.jpg");
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($retcode == '200')
        $image .= "<a href=http://www.domain.com/feeds/fort/rets_images/{$ListingRid}_{$c_ext}.jpg rel=\"enlargeimage\" rev=\"targetdiv:loadarea,trigger:click\" title=\"\"><img src=http://www.domain.com/feeds/fort/rets_images/{$ListingRid}_{$c_ext}.jpg title='' width='100' height='75' border='0' /></a>";
    else
    $c=31;

    $img_cnt++;
}
?>

1 个答案:

答案 0 :(得分:2)

你的问题是myagentsbuddy.com在找不到图像时没有返回404。我检查了你的一个破碎的图像和curl -I,它给了我200.你最好检查它的内容类型,看看它是图像/ *还是text / html。

以下是我对现有图片的了解:

$ curl -I http://www.myagentsbuddy.com/feeds/fort/rets_images/2332012_8.jpg
HTTP/1.1 200 OK
Date: Tue, 07 Oct 2014 12:20:16 GMT
Server: Apache
Last-Modified: Fri, 21 Feb 2014 18:03:02 GMT
ETag: "4e75339-647c-6ece6180"
Accept-Ranges: bytes
Content-Length: 25724
X-Powered-By: PleskLin
Connection: close
Content-Type: image/jpeg

对于破碎的图像:

$ curl -I http://www.myagentsbuddy.com/feeds/fort/rets_images/2332012_9.jpg
HTTP/1.1 200 OK
Date: Tue, 07 Oct 2014 12:18:42 GMT
Server: Apache
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
Pragma: no-cache
X-Pingback: http://www.myagentsbuddy.com/xmlrpc.php
Last-Modified: Tue, 07 Oct 2014 12:18:42 GMT
X-Powered-By: PleskLin
Connection: close
Content-Type: text/html; charset=UTF-8

查看两者的最后几行。有区别。

所以你需要:

$image = "<div class='wrap_img_small'><br>";
$ListingRid = $row['matrix_unique_id'];
$img_cnt = 1;
for ($c=1;$c<25;$c++) {
    $c_ext = $c;
    $ch = curl_init("http://www.myagentsbuddy.com/feeds/fort/rets_images/{$ListingRid}_{$c_ext}.jpg");
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $contenttype = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    curl_close($ch);
    if (strpos($contenttype, 'image') === false) break;
    $image .= "<a href=http://www.myagentsbuddy.com/feeds/fort/rets_images/{$ListingRid}_{$c_ext}.jpg rel=\"enlargeimage\" rev=\"targetdiv:loadarea,trigger:click\" title=\"\"><img src=http://www.myagentsbuddy.com/feeds/fort/rets_images/{$ListingRid}_{$c_ext}.jpg title='' width='100' height='75' border='0' /></a>";

    $img_cnt++;
}