Search code examples
phppathincluderelative-path

PHP 'include' issue - cannot seem to get include to work correctly


I'm having a spot of bother with php includes. I have the following file structure

htdocs

  • index.php
  • login.php

php_includes

  • db_conx.php
  • check_user_status.php

within the db_conx.php file i've creates a variable $number = 10; for testing.

The db_conx file is included in the check_user_status.php file with the following code:

include_once("db_conx.php");

and that is working fine - i.e. i can echo $number and get 10.

However, I'm including the check_user_status.php file at the top of login.php with this code:

include_once("php_includes/db_conx.php");

and on this page I'm unable to echo out $number on this page (check_user_status.php).

I'm going to need this script included in many pages (since it checks whether the user is logged in or not). Am I doing something strange with the paths?


Solution

  • For relative paths you need to do this.

    include_once("../php_includes/db_conx.php");
    

    To break this down.

    Your Current working directory is initially going to be htdocs/ if your hit that file in your browser.

    the .. back you up one directory level (so the directory that contains both htdocs and php_includes)

    then you want to follow down php_includes to get to db_conx.php.

    This will become a problem when you do a file in a subdirectory. Assuming you and a page2.php to a htdocs/subpages/

    Now if we follow those same steps we are not going to arrive at the same location.

    A better approach is to get the path relative to an absolute location. I like using the document root (htdocs in your case), so:

     include($_SERVER["DOCUMENT_ROOT"]."/../php_includes/db_conx.php");
    

    will refer to the same place on the file system regardless of where it is used.