Search code examples
phpfile-exists

file_exists() not working as expected


In the code below, file_exists() is not working as expected. Even when I'm trying to upload the same file, the else part gets executed. (ie file_exists() returns false in every case.) What is the reason behind this behavior?

if (isset($_FILES['file']['name']) && isset($_FILES['file']['size']) && isset($_FILES['file']['type']) && isset($_FILES['file']['tmp_name']))
{
    if (!empty($_FILES['file']['name']) && strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION))=='jpg' || strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION))=='jpeg')
    {
        if(file_exists($_FILES['file']['name']))
        {
           echo 'file exists';
        }
        else
        {
           move_uploaded_file($_FILES['file']['tmp_name'], 'Images/'.$_FILES['file']['name']);

           echo $_FILES['file']['name'].' Uploaded'.'<br>';
        }
     }
}
else{ 
     echo 'select your file';
    }

Solution

  • The problem

    When you use file_exists, you only use the short name of the file.

    if(file_exists($_FILES['file']['name']))
    

    For example, if you upload a file called test.jpg, it checks if ./test.jpg exists.

    But, when you actually move the uploaded file, you put it in a directory called Images:

    move_uploaded_file($_FILES['file']['tmp_name'], 'Images/'.$_FILES['file']['name']);
    

    Now, if you upload that test.jpg, it's moved to ./Images/test.jpg, which isn't found by your other code.

    The solution

    You should use the same file name in both cases. So, just change the if with the file_exists call to:

    if(file_exists('Images/'.$_FILES['file']['name']))
    

    This code adds the folder name to the file name, so that you check for the correct path; uploading test.jpg leads to checking the file ./Images/test.jpg.