note 35227 deleted from function.realpath by aidan

From: Date: Sun, 29 Aug 2004 21:50:34 +0000
Subject: note 35227 deleted from function.realpath by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-75608@lists.php.net to get a copy of this message
Note Submitter: dave at birko dot cjb dot net ---- This function is kind of reversed version of realpath. It takes canonical ("absolute") path to a filename, $pic, and returns path relative to the script's directory. I had to code it by myself as no similar routine was to be found on the net. "POSIX" behaviour. Tested on *nix. Example: The script is http://hostname/scripts/me.php (realpath is /var/www/application/scripts/me.php) and has only absolute path to a picture (/var/www/data/pictures/image.jpg) it's about to display using the tag <IMG> (which doesn't accept absolute paths). $rel = traverse_path("/var/www/data/pictures/image.jpg"); echo $rel; ../../data/pictures/image.jpg The Code: function traverse_path($pic) { $from = dirname(realpath($_SERVER['DOCUMENT_ROOT']. $_SERVER['SCRIPT_NAME'])); $to = dirname(realpath($pic)); $path = "../"; $i = 0; // Find diff or the end of one of them while (($from[$i] == $to[$i]) && $from[$i] && $to[$i++]); $p = $i; if (!$from[$i] && ($to[$i] == "/" || !$to[$i])) { // $pic is in our (sub)directory return ("./".substr($pic, $i+1, strlen($pic))); } else { // $pic is outside our dir branch // find out how many "../"'s are necessary while ($from[++$i]) { if ($from[$i] == "/") $path .= "../"; } // Find the first common dir while ($to[--$p] != "/" && $to[$p]); return ($path.substr($pic, $p+1, strlen($pic))); } } note: on some servers, $from = dirname(realpath($_SERVER['SCRIPT_FILENAME'])) should be used instead of $from = dirname(realpath($_SERVER['DOCUMENT_ROOT'].                 $_SERVER['SCRIPT_NAME'])); Any fixes, ideas, etc. to my mail. Thx! :)

« previous php.notes (#75608) next »