Is anyone able to explain why, if the file_exists() function expects/requires an absolute (as opposed to relative) path to the file, the second of the three lines of code in the example below returns TRUE? That is a relative path, but the function still returns TRUE.

Basically, I'm trying to figure out why if the second example returns TRUE, the first example does not also return TRUE, since both use relative paths.

//This example makes use of Apache 2 on the Windows platform.
//The "movie.flv" file is located at D:\My Documents\Apache\siteroot\player\flv\movie.flv

//For reference, this example script is located in the Apache's document root: D:\My Documents\Apache\script.php

//Returns FALSE.
var_dump(file_exists('/siteroot/player/flv/movie.flv'));

//Returns TRUE.
var_dump(file_exists('./siteroot/player/flv/movie.flv'));

//Returns TRUE.
var_dump(file_exists('D:\My Documents\Apache\siteroot\player\flv\movie.flv'));

Thanks for any insight...

    The first example is not a relative path.

    Who says file_exists requires an absolute path?

      Thanks for your reply, Weedpacket.

      Sorry, you're right; the first example is not a relative path. It is indeed an absolute path. My mistake.

      I probably should have asked, "Why does the first example return FALSE?"

      Here is another example, again, using "script.php", which is located in Apache's document root:

      //Returns FALSE.
      file_exists('/script.php');
      
      //Returns TRUE.
      file_exists('./script.php');
      

      If indeed file_exists() will accept either an absolute or a relative path, why do both lines of code in the above example not return TRUE?

      Thanks!

        The first line is absolute, so it is looking for a file in / .
        The second one looks in apache root which is unlikely to be /

          Do not confuse the '/pathname' format used in [X]HTML with the file system path being used by file_exists() and other file system-related PHP function. On a UNIX/Linux file system, '/' refers to the root directory on the current logical disk. It does not refer to your web document root directory as it would in a web page 'src' or 'href' attribute.

          If you want to reference files in relation to your web document root regardless of where the currently running script is located, use $SERVER['DOCUMENT_ROOT']:

          file_exists($_SERVER['DOCUMENT_ROOT'].'/path/to/file.php');
          

          ($_SERVER['DOCUMENT_ROOT'] will resolve to something like '/home/username/public_html' or whatever your web document root is.)

            Thanks, NogDog!

            That's exactly the explanation I was looking for. You nailed it. Very clear, very concise, and polite (which is not often the case around here). My script now functions (pardon the pun) as intended.

            Best,

            Ben

              Write a Reply...