Search code examples
phpfile-existsdocument-rootserver-variablesvirtual-path

server variable document root is not playing nice with file_exists when virtual folder is involved


I've got a virtual folder on IIS. When I do a server document root, I'm not getting file_exists find the files. But interestingly, if I use include (or require directives for that matter) same files being found.

example

$full_path = $_server['DOCUMENT_ROOT'] . "/file.txt";
include($full_path); // works fine. 
if file_exists($full_path) : // returns false!

Again, this is only when I have a virtual folder involved.

I guess I have to use a different server variable which is not effected by whether there is a virtual folder or not.

eventually, I'd like the following to work

/wwwroot/file.txt should be found with this

file_exists($_server['?'] . "/file.txt")


Solution

  • Use a config file and define baseroot and publicroot.

    <?php
    // myconfig.php -- stored in the public root
    $direx = explode("/", getcwd());
    DEFINE ('BASEROOT', '/'.$direx[1].'/'.$direx[2].'/'); // host/mysite/
    DEFINE ('PUBLICROOT', '/'.$direx[1].'/'.$direx[2].'/'.$direx[3].'/'); // host/mysite/public_html/
    ?>
    
    <?php
    require_once('myconfig.php'); // called on every page
    
    IF (File_Exists(PUBLICROOT.'some_folder/file.txt')) { /* do something */ }
    
    include_once(PUBLICROOT.'some_folder/file.txt');
    ?>