c.k c.k - 5 months ago 15
PHP Question

Check if Image file name exists php loop

I have multiple images on my root folder

/images/filename.here
. Image filenames are like this (email):
me@yahoo.jpg
,
me@yahoo_1.jpg
,
me@yahoo_2.jpg
,
you@gmail.jpg
.

My code on showing only one image of user if exist
me@yahoo.jpg
and
you@gmail.jpg
:

<?
$email= $data['payment']['email'];
$receipts = "images/".$email;
if (file_exists($receipts)) { ?>
<img src="<?=($receipts)?>" width:"100px" height="50px"/>
<? } else {
echo "no receipt";
} ?>


this only show the "without
_x
" filename. How can I show other images of a user(e.g me@yahoo) using loop
_1
,
_2
,
_3
... It should display all images that belong to a user.

Answer

I would create a helper function get_image to return the path of the image by email and index, and use a while loop to build the list of images:

<?php
function get_image($email, $i) {
    $path = "images/receipts/".$email;
    if ($i > 0) $path .= '_' . $i;
    $path .= '.jpg';
    if (file_exists($path)) return $path;
    return null;
}

$i = 0;
while ($path = get_image($email, $i)) {
    echo "<img src=\"$path\" width:\"100px\" height=\"50px\"/>";
    $i++;
} 

if ($i == 0) {
    echo "no receipt";
}
?>