Search code examples
phpserverrelative-pathabsolute-pathlocalserver

Work with paths on localserver and normalserver


I have a problem. I want to use a localserver (WAMP) and an online server (000webhost) at the same time. Now there is a problem with my file paths. I can not use normal paths like (../contact.php) because I use php include files and then the path will be different because I include the file over the whole site.

Now I wanted to use absolute paths like (/main/includes/header.inc.php) But the root folder on the online server and local server are different, so that won't work too.

Are there any solutions I can use?

Jelmer


Solution

  • Set a web root directory constant ROOT that you can use to load your file paths. For each server set this to their path accordingly. Make sure that is loaded at the top of the first file hit for each request.

    <?php
    define('ROOT', `/var/www/html/site`);
    ...
    

    now load your files with the constant

    include ROOT . '/directory/file.php';
    

    Obviously set constant different for each server.

    You could put your define() in an if statement as well.

    <?php
    if($_SERVER['SERVER_NAME'] === 'localhost'){
        define('ROOT','/wamp/dir/'); //obviously not your actual dir
    }else{
        define('ROOT','/online/dir/'); //obviously not your actual dir 
    }
    

    UPDATE

    Better idea might beusing environment variables instead of conts.

    Setting CONST on every page is a bit tedious. I found this post that explains how to set an environment variable in the .htaccess. that way we only need to set it in once place and can access it in all files.

    eg:

    //.htaccess
    SetEnv ROOT /var_www/html/site/
    

    Now I can get this value with this in all my .php files:

    <?php
    include getenv('ROOT'); . '/directory/file.php';
    

    credit:

    store constant variable on server via .htaccess