Eddy_Kay
Eddy_Kay

Reputation: 67

Broken Images appearing when no image is present php while loop

Hi I managed to create an image display page on php, and it works, the only issue is that it displays broken images as well with the image url showing just the folder path. My code is below with a screen shot of the final page. Is there any thing I am doing wrong?

<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;
?>

This is the final out come as a screenshot, as you can see only one image is correct, the first two don't exist. Screenshot containing broken image

Upvotes: 0

Views: 203

Answers (2)

kscherrer
kscherrer

Reputation: 5766

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

this if returns always true, try this instead:

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

Edit: as Dainis Abols pointed out, you can write it with a single condition using in_array(). This way, you can even easily add more allowed extensions into the array

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

Upvotes: 2

Naincy
Naincy

Reputation: 2943

Before sending path of image to the img tag. Check if that file exist or not with file_exists function of php to avoid showing broken links.

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

Upvotes: 0

Related Questions