douran7929 2013-01-29 20:05 采纳率: 100%
浏览 22
已采纳

使用file_exists检查echo之前是否存在图像

I'm trying to let my script check if an image exist before echoing it into my table. If it doesn't exist, it should echo another image in stead. My problem is that even though the image exist, it still goes to the else factor. Can anyone spot any coding mistakes?

<?php
mysql_select_db("xxxx");
$result = mysql_query("SELECT * FROM yyyy WHERE frivillig=1 ORDER BY stilling");
while($row = mysql_fetch_array($result))
{
?>
<tr>
<td width="50px" class="frivillig"><?php  if (file_exists($url . "ansatte" . "/" . (utf8_encode($row['etternavn'])) . "%20" . (utf8_encode($row['fornavn'])) . ".jpg")) {
echo "<img" . " " . "src='" . $url . "ansatte" . "/" . (utf8_encode($row['etternavn'])) . "%20" . (utf8_encode($row['fornavn'])) . ".jpg'" . " " . "height='50px'/>";
}
else {
echo "<img" . " " . "src='" . $url . "images/mangler.png'" . " " . "height='50px'/>";
}
?>

As you can see, I use $url for my complete url, and the images are placed in the /ansatte/ folder.

Thanks for any help!

  • 写回答

3条回答 默认 最新

  • dongzhong2018 2013-01-29 20:11
    关注

    Consider the below snippet for checking remote resources:

    $path = $url . "ansatte" . "/" . (utf8_encode($row['etternavn'])) . "%20" . (utf8_encode($row['fornavn'])) . ".jpg"
    
    $ch = curl_init($path);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_NOBODY, TRUE);
    $response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpcode < 400) { // Filter out bad request, not found, etc
     // found
    } else {
     // not accessible
    }
    

    If you don't have php5-curl installed, you could also look at the following alternatives:

    getimagesize

    Again only certain streams are supported here, but usage is simple and it will validate the return better:

    if (getimagesize($path) !== FALSE) {
      //exists
    }
    

    fopen

    if (fopen($path,"r") !== FALSE) {
      // exists
    }
    

    get_headers

    $headers = get_headers($path, TRUE);
    if ($headers !== false && isset($headers['Content-Type']) && $headers['Content-Type'] == 'image/jpeg') {
      // exists
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路