在循环时没有图像存在时出现的断开图像

时间:2017-02-08 08:12:23

标签: php image

您好我设法在php上创建了一个图像显示页面,并且它可以工作,唯一的问题是它显示损坏的图像以及图像URL仅显示文件夹路径。我的代码在下面是最后一页的屏幕截图。我有什么问题吗?

<form method='post' action='display_images.php'
enctype='multipart/form-data'>
<div class="panel-body">
<div id="tab-4" class="tab-pane">
<div class="table-responsive">
<table class="table table-bordered table-stripped">

  <?php
echo <<<_END
<thead>
  <tr>
  <th>
   Image preview
               </th>
                <th>
                 Image url
                  </th>

                  <th>
                   Actions
                     </th>
                     </tr>
                     </thead> 
_END;

$folder = "../inventory_images";
$filesInFolder = new DirectoryIterator($folder);
while($filesInFolder->valid()){
$file = $filesInFolder->current();
$filename = $file->getFilename();
$src = "$folder/$filename";
$extension = $file->getExtension();
$extension = strtolower($extension);

if ( $extension === 'jpg' || 'png'){
$href = "display_images.php?delete-image=$src";
$img = "<td><img src='$src' height = '100px' width = '100px'></td>";
$input = "<td><input type='text' class='form-control' disabled value='$src'></td>"; 
}
$filesInFolder->next();

echo"<tbody>";
echo "<tr>";
echo"$img";
echo"$input";
echo"<td><a href='$href' class='btn btn-white'><i class='fa fa-trash'></i></a></td>";
echo"</tr>";    
echo"</tbody>";             
}
echo <<<_END
</table>
</div>
</div>
</div>
</form>
_END;
?>

这是最后的截图,因为你只能看到一张图片是正确的,前两张图片不存在。 Screenshot containing broken image

2 个答案:

答案 0 :(得分:2)

if ( $extension === 'jpg' || 'png'){

如果返回始终为true,请尝试此操作:

if ( $extension === 'jpg' || $extension === 'png'){

编辑:正如Dainis Abols指出的那样,您可以使用in_array()在一个条件下编写它。这样,您甚至可以轻松地将更多允许的扩展添加到数组中

if (in_array($extenion, ['jpg', 'png'])){

答案 1 :(得分:0)

在将图像路径发送到img标记之前。 使用php的file_exists函数检查该文件是否存在,以避免显示断开的链接。

价: http://www.w3schools.com/php/func_filesystem_file_exists.asp