How do I check if a file exists?

0

I used the file_exists function and it even finds the file.

The problem is that when it does not find, the message that does not exist does not appear (it does not go into the else).

<?php
    $email = $v->email;
    $email = strstr($email, '@', true);
    $url = base_url();
    foreach (array('png', 'jpg', 'gif') as $ext) {
        if (!file_exists("./uploads/{$email}." . $ext)) {
            continue;
        }
        $email = "$email.$ext";

        $filename = "./uploads/{$email}";


        if (file_exists($filename)) {
            echo "O arquivo $filename existe";
        } else {
            echo "O arquivo $filename não existe";
        }

        echo "<img alt='' class='left avatar-comentario' src=\"" . $url . "uploads/$email\" maxwidth=\"300\" ,maxheight=\"400\" />";
        break;
    }
?>
    
asked by anonymous 23.02.2017 / 15:25

1 answer

2

This is because you check the file twice, and at first you run continue if the file does not exist. The continue causes the current iteration to be finalized and thus the second if is not executed.

What you can do is remove the first if :

foreach (array('png', 'jpg', 'gif') as $ext) 
{
    $email = "$email.$ext";
    $filename = "./uploads/{$email}";

    if (file_exists($filename)) {
        echo "O arquivo $filename existe";
        echo "<img alt='' class='left avatar-comentario' src=\"" . $url . "uploads/$email\" maxwidth=\"300\" ,maxheight=\"400\" />";
        break;
    } else {
        echo "O arquivo $filename não existe";
    }
}

In this way, it would work, but several messages would appear on the page. An interesting way to do is to maintain a generic avatar image and, if the system finds the file, replace the image. Something like:

$avatar = "./uploads/avatar.png";

foreach(array("png", "jpg", "gif") as $ext)
{
    $filename = "./uploads/{$email}.{$ext}";

    if (file_exists($filename))
    {
        $avatar = $filename;
        break;
    }
}

echo "<img ... src=\"{$avatar}\" />"

In this way, if the system does not find any of the files, the genre avatar uploads/avatar.png is displayed, but if it does, it displays the found image.

    
23.02.2017 / 16:06