繁体   English   中英

PHP检查图像是否存在,如果不存在则返回文本

[英]PHP check image if exists and return a text if not

我找到了这个解决方案,因为@getimagesize太慢了:

function get_image_by_id($ID)
{
$url = $ID;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
$info = curl_getinfo($ch);
if(file_get_contents($url) == NULL)
{
    return NULL;
}
else
{
    return $url;
}
}

它的运行速度非常快,但是即使该图像不存在,该功能也会始终尝试加载该图像。 这是我实现代码的方法:

<?php if (get_image_by_id($link)): ?>
    <?php echo '<img src="' . $link . '" alt="' . $propname . '" />'; ?>
<?php endif; ?>

我只需要一个不存在的图像,然后仅从数组中回显$propname

使用is_null可以工作,但它的速度与@getimagesize相同(慢)。

所以现在其他看起来像:

<?php if (is_null(get_image_by_id($link))): ?>
    <?php echo $propname; ?>
<?php endif; ?>

我该如何快速编写代码:

if(image_exists($link) {
echo $image;
} else {
echo $propname;
}

使用Curl返回状态以识别图像的存在

<?php
    function image_exist($url){
        $ch = curl_init($url);    
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if($code == 200){
           $status = true;
        }else{
          $status = false;
        }
        curl_close($ch);
       return $status;
    }
    ?>

您可以进行测试以查看卷曲响应,如果有,请执行以下代码:

$output=curl_exec($ch);
if ($output === false || $info['http_code'] != 200) {
  //$output = "No cURL data returned for $url [". $info['http_code']. "]";
  //if (curl_error($ch))
  //  $output .= "\n". curl_error($ch);
  //}
  return null; //or $output
else {
  // 'OK' status; format $output data if necessary here: 
  return $url;
}

不要忘记关闭curl连接curl_close($ch);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM