File There is PHP

4

I'm 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, could someone explain me?

    
asked by anonymous 24.11.2015 / 03:15

1 answer

4

Prank of the Trickster 1:

The file_exists() function, despite the name, checks to see if the path exists, independently of it being a file or directory.

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

if (file_exists( '/pasta/' ))

which should return true if the folder actually exists.

Solution:

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

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

If you want to check folders / directories only, there is the is_dir() function, which check if the path exists and it's directory.

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


Prank of the trickster 2:

Caution if you need to check files shortly after changing something in the filesystem, because all the above functions have a cache in PHP.

Solution:

To make sure you're dealing with the updated path, there's 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 the names of the above functions to find out more details, they are linked with the PHP online documentation.

    
24.11.2015 / 03:33