Assuming this is how your web folder looks
root
/includes
/relativeroot1
/relativeroot2
Create a file named path.php
in the includes
folder above and insert the following
<?php
if (session_id() == '') {
session_start(); /* if not already done */
}
/* replace value below with appropriate header to root distance of this include file */
$header_to_root_distance = 1;
$header_dir = dirname(__FILE__);
$root_distance = substr_count($header_dir, DIRECTORY_SEPARATOR) - $header_to_root_distance;
if($_SERVER['SERVER_ADDR']){
$include_distance = substr_count(dirname($_SERVER['SCRIPT_FILENAME']), "/");
}else{
$include_distance = substr_count(dirname($_SERVER['SCRIPT_FILENAME']), "\\");
}
$r_path = str_repeat('../', $include_distance - $root_distance);
$_SESSION['r_path'] = $r_path;
/* Note - $r_path holds your relative url starting from the root folder */
?>
Create a .htaccess
file in the root
folder above and insert the following
<IfModule php5_module>
php_value include_path "includes/"
</IfModule>
Now open the file you want a relative path e.g your myphp.php
script and insert the following at the top
<?php require 'path.php' ?>
So to request for any relative path from any file in your case. Just do the following
<img src="<?php echo $r_path.'relativeroot2/img.jpg' ?>" title="My Image" />