File Exists PHP

Asked

Viewed 893 times

4

I am using this function to check if the file exists:

<?php
    header('Content-Type: text/html; charset=utf-8');
    //header('Accept-Ranges: bytes');

    $nome_real = $_FILES["Arquivo"]["name"];
    $pastadestino = "/pasta/$nome_real";

    //verifica antes de passar - para apagar o existente
    if (file_exists($pastadestino))
    {
        echo "OK";
    }
    else
    {
        echo "NOK";
    }
?>

However, it returns OK even if I leave the path empty. Or even if the file name is different, someone could explain me?

  • It seems all right to me... here it is NOK, see on ideone.

1 answer

5


Trickster of the rascal 1:

The function file_exists(), despite the name, checks if the path exists, regardless of whether it is a file or directory.

When you leave the parameter empty, your test is the same as this:

if (file_exists( '/pasta/' ))

what should return true if the folder actually exists.

Solution:

The solution would be to exchange the function for is_file(), which is specific to files:

if (is_file($pastadestino))
    {
        echo "OK";
    }
    else
    {
        echo "NOK";
    }

If you want to check folders/directories only, there is the analog function is_dir(), that check if the path exists and is directory.

if (is_dir($pastadestino))
    {
        echo "OK";
    }
    else
    {
        echo "NOK";
    }


Trickster of the rascal 2:

Be careful if you need to scan files right after changing something in the filesystem, as all of the above functions have a cache in PHP.

Solution:

To make sure you are dealing with the updated path, there is the clearstatcache():

clearstatcache(); // Limpamos o cache de arquivos do PHP
if (is_file($pastadestino)) // is_dir() para pastas, is_file para arquivos.
    {
        echo "OK";
    }
    else
    {
        echo "NOK";
    }

Click on the names of the above functions to know more details, they are linked with online PHP documentation.

  • then if I update my . php file and by this way, it will check whether the file identified in the path is valid or not?

  • 2

    It depends on what you call valid. The way I put it is to check whether the file in the given path exists or not. If it doesn’t work, you need to check that the variable value is correct. For folders, is_dir(). For files, is_file().

  • 1

    Okay, that’s right, thank you Bacco.

Browser other questions tagged

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