Search code examples
phpfilenamesntfsfile-exists

PHP, file exists: 'con'?


I made 2 checks of file name validness (for uploading):

  1. Is there another file with the same name?
  2. Can a file with this name be created at all?

For (1) I use file_exists, for (2) — fopen for creating.

$dir = '../../images/';
if (file_exists($dir.$name))
{
    ok('alreadyexists', 'true');
}
else
{
    $file = fopen($dir.$name, 'x');
    if (FALSE == $file)
    {
        ok('invalid', 'true');
    }
    else
    {
        fclose($file);
        ok();
    }
}

Testing the code above, I tried the name 'con' (AFAIK, under Windows you can't create such files). I supposed it would fail at the second test, but file_exists returns true for '../../images/con'! Why?


Solution

  • I suggest to use is_writable($dir.$name) after the file has been touched / created (files get saved AFTER fclose). touch() is also a good approach for initially creating a file and test wether it can be written.

    Could try:

    touch($dir.$name);
    
    is_writable($dir.$name);
    
    //parse the output of
    shell_exec('touch ' . $dir . $name);
    // or
    exec('touch ' . $dir . $name);
    

    Would also be interesting what this prints:

    filetype($dir.$name);
    

    From http://www.php.net/manual/en/function.filetype.php

    There are 7 values that can be returned. Here is a list of them and what each one means block: block special device char: character special device dir: directory fifo: FIFO (named pipe) file: regular file link: symbolic link unknown: unknown file type

    // also interesting:
    stat($dir.$name);