【问题标题】:Broken Images appearing when no image is present php while loop当没有图像存在php while循环时出现破碎的图像
【发布时间】:2017-02-08 08:12:23
【问题描述】:

嗨,我设法在 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

【问题讨论】:

  • 你想怎么样?

标签: php image


【解决方案1】:
if ( $extension === 'jpg' || 'png'){

如果返回总是 true,试试这个:

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

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

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

【讨论】:

  • 或者,如果需要更多案例,可以将其缩短为if (in_array($extension, ['jpg', 'png', 'gif'])) {}
【解决方案2】:

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

参考: http://www.w3schools.com/php/func_filesystem_file_exists.asp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-06
    • 2015-09-02
    • 2018-10-07
    • 2017-04-07
    • 1970-01-01
    • 2017-10-28
    • 2023-03-25
    • 2021-08-10
    相关资源
    最近更新 更多