Search code examples
phpfileinclude-path

include_once, relative path in php


I have 3 files: home, failed_attempt, login.

The file home and failed_attempt all refer to login file.

The annoying thing is that they throw a mistake saying that the login file doesnt exist. home will throw an exception if i do this, but failed_attempt wont.

  include_once("../StoredProcedure/connect.php");

include_once("../untitled/sanitize_string.php");

and if I do this:

   include_once("StoredProcedure/connect.php");
   include_once("untitled/sanitize_string.php");

the opposite happens, failed_attempt throws an exception , but home, wont. How do I fix this..

Do I tell the include to go up a page by putting this ../ , and therefore home.php doesnt need to go one page up therefore it throws that exception..

How can I make it so both files accept those inclueds as valid.. perhaps not relative to where they are placed.. i.e. without that ../

Directory structure:

PoliticalForum
->home.php
->StoredProcedure/connect.php
->untitled/sanitize_string.php
->And other irrelevant files

Solution

  • Here are three possible solutions. The second are really just work-arounds that use absolute paths in a clever way.

    1: chdir into the correct directory

    <?php
    
    // check if the 'StoredProcedure' folder exists in the current directory
    // while it doesn't exist in the current directory, move current 
    // directory up one level.
    //
    // This while loop will keep moving up the directory tree until the
    // current directory contains the 'StoredProcedure' folder.
    //
    while (! file_exists('StoredProcedure') )
        chdir('..');
    
    include_once "StoredProcedure/connect.php";
    // ...
    ?>
    

    Note that this will only work if your StoredProcedure folder is in the topmost directory of any files that might need to include the files it contains.

    2: Use absolute paths

    Now before you say this is not portable, it actually depends on how you implement it. Here's an example that works with Apache:

    <?php
    include_once $_SERVER['DOCUMENT_ROOT'] . "/StoredProcedure/connect.php";
    // ...
    ?>
    

    Alternatively, again with apache, put the following in your .htaccess in the root directory:

    php_value auto_prepend_file /path/to/example.php
    

    Then in example.php:

    <?php
    
    define('MY_DOC_ROOT', '/path/to/docroot');
    
    ?>
    

    And finally in your files:

    <?php
    include_once MY_DOC_ROOT . "/StoredProcedure/connect.php";
    // ...
    ?>
    

    3: Set PHP's include_path

    See the manual entry for the include_path directive. If you don't have access to php.ini, then this can be set in .htaccess, providing you are using Apache and PHP is not installed as CGI, like so:

    php_value include_path '/path/to/my/includes/folder:/path/to/another/includes/folder'