Posted By

blackhole12 on 06/30/09


Tagged

php dir relative root


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

chrisjlee
blackhole12
BrianCoyDesign


Get Relative Path to Root Directory


 / Published in: PHP
 

URL: www.blackspherestudios.net

There's another snippet on here that always comes up on google for finding the relative path to the root, but it doesn't work very well. This version will work from the root, from any subdirectory, and with malformed path names such as www.example.com/////dir////path///file.php

What I have here is designed to be pasted at the top of a php file, but you can also stick it inside a function and return $relpath.

  1. $relpath = "";
  2. $tempvar_relpathdir = explode("/",dirname($_SERVER['PHP_SELF']));
  3. for($i=count($tempvar_relpathdir); $i>0; $i--) if($tempvar_relpathdir[$i] != '') $relpath .= "../";

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: blackhole12 on July 7, 2009

BUGFIX: for($i=count($tempvar_relpathdir); $i>0; $i--) should instead be for($i=count($tempvar_relpathdir)-1; $i>0; $i--) It actually works without this bugfix almost all of the time (which is odd because it technically shouldn't), but it'll spew out a notice when including one php file from another. This fixes that.

You need to login to post a comment.