How to walk back N directories

While scanning a directory tree I run into the following situation; Consider you have the following three paths:

– /home/project/user/www/ (web root folder )
– /home/project/user/www/images (folder for images )
– /home/project/user/www/include/dummy/script.php (script to handle images )

The problem was, that the function to scan the images folder (tree) in script.php did not handle absolute path properly (access rights?). So I was looking for a solution to give the relative path from the working directory of script.php back to the absolute path. The following few lines in PHP did it quite well:

$p1 = substr_count(realpath(ABSPATH), DIRECTORY_SEPARATOR);
$p2 = substr_count(realpath(dirname(__FILE__)), DIRECTORY_SEPARATOR);
for($j=0;$j< ($p2-$p1);$j++) $ret .= \”../\”;
echo $relative_path = $ret . ltrim($image_base_dir, DIRECTORY_SEPARATOR);

A possible result would be \”../../images\”, while $image_base_dir is set to \”images\”. Eventually I missed a simple function this topic easier, if so, let me know 😉

Leave a Reply