How do I check for a file?

Asked

Viewed 519 times

0

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

The problem is that when it does not find, the message that does not exist is not displayed (it does not enter 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;
    }
?>

1 answer

2


This is because you check the existence of the file twice and at first you run continue if the file does not exist. The continue causes the current iteration to be completed 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";
    }
}

This way it would work, but would appear several messages on the page. An interesting way to do it is to keep 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}\" />"

This way, if the system does not find any of the files, the generic avatar is displayed uploads/avatar.png, but if found, displays the image found.

  • Thank you Anderson, your reply helped me!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.