Saturday 27 June 2015

Get Relative Path to Website Root for Includes to Access from Anywhere

If you have files in different directories that include a php file which also includes other file, a problem can be the patch that can changes when the file is included from different level of directories.
For example, in this files and folders structure:
/
- dir1/
  - dir1_2/
      level_2.php

  level_1.php

config.php
index.php
- "level_1.php" (which is in "dir1/") include "config.php".
- "level_2.php" (which is in "dir1_2/") include "level_1.php".
- "index.php" (in root "/") include "level_1.php".

As you can notice, "level_1.php" is included from root (in "index") and from "dir1_2/" (in "level_2").
If in 'level_1.php' we include "config.php" using:
include('../config.php');
This code will not work when "level_1.php" is included in the other files.

The problem is, how to include "config.php" in "level_1.php" so this file can be accessed from anywhere?
I tried with absolute /full server path, using:   dirname(__FILE__) (or: __DIR__ ), but didn't work in Windows.
After searching on the net to find a proper solution to this problem, I found the following code, that gets the relative path to Web Site Root directory ("www/", "public_html/", "httpdocs/"):
$current_path = pathinfo($_SERVER['SCRIPT_NAME'], PATHINFO_DIRNAME);
$current_host = pathinfo($_SERVER['REMOTE_ADDR'], PATHINFO_BASENAME);
$the_depth = substr_count( $current_path , '/');

// Set path to root for includes to access from anywhere
if($current_host == '127.0.0.1') $pathtoroot = str_repeat('../' , $the_depth-1);
else $pathtoroot = str_repeat ('../' , $the_depth);

echo $pathtoroot;

I put this code into a function that returns the relative path to Web Site Root directory from any current folder, and the problem was solved using this function to include "config.php" in "level_1.php", that can be accessed from anywhere.
// returns the relative path from current folder to Web Site Root directory
function getRootPath() {
  $current_path = pathinfo($_SERVER['SCRIPT_NAME'], PATHINFO_DIRNAME);
  $current_host = pathinfo($_SERVER['REMOTE_ADDR'], PATHINFO_BASENAME);
  $the_depth = substr_count( $current_path , '/');

  // Set path to root for includes to access from anywhere
  if($current_host == '127.0.0.1') $pathtoroot = str_repeat('../' , $the_depth-1);
  else $pathtoroot = str_repeat ('../' , $the_depth);

  return $pathtoroot;
}

// include file located in root
include(getRootPath(). 'config.php');

0 comments:

Post a Comment