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条)

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题