note 78567 added to function.realpath

From: Date: Wed, 17 Oct 2007 18:10:06 +0000
Subject: note 78567 added to function.realpath
Groups: php.notes 
Request: Send a blank email to php-notes+get-131459@lists.php.net to get a copy of this message
Santosh Patnaik's method worked in most cases, but when I gave it funky input with different directory separators it returned the wrong path. I liked julabz at laposte dot net the best, and modified it to use a similar signiture signature to Patnaik's function: <?php function unrealpath($start_dir, $final_dir, $dirsep = DIRECTORY_SEPARATOR){ //Directory separator consistency $start_dir = str_replace('/',$dirsep,$start_dir); $final_dir = str_replace('/',$dirsep,$final_dir); $start_dir = str_replace('\\',$dirsep,$start_dir); $final_dir = str_replace('\\',$dirsep,$final_dir); //'Splode! $firstPathParts = explode($dirsep, $start_dir); $secondPathParts = explode($dirsep, $final_dir); //Get the number of parts that are the same. $sameCounter = 0; for($i = 0; $i < min( count($firstPathParts), count($secondPathParts) ); $i++) { if( strtolower($firstPathParts[$i]) !== strtolower($secondPathParts[$i]) ) { break; } $sameCounter++; } //If they do not share any common directories/roots, just return 2nd path. if( $sameCounter == 0 ) { return $final_dir; } //init newpath. $newPath = ''; //Go up the directory structure count(firstpathparts)-sameCounter times (so, go up number of non-matching parts in the first path.) for($i = $sameCounter; $i < count($firstPathParts); $i++) { if( $i > $sameCounter ) { $newPath .= $dirsep; } $newPath .= ".."; } //if we did not have to go up at all, we're still in start_dir. if( strlen($newPath) == 0 ) { $newPath = "."; } //now we go down as much as needed to get to final_dir. for($i = $sameCounter; $i < count($secondPathParts); $i++) { $newPath .= $dirsep; $newPath .= $secondPathParts[$i]; } // return $newPath; } ?> The only error I found in julabz's function was that count is always 1 for any string, but strlen does what he intended in this case. ---- Server IP: 208.69.120.35 Probable Submitter: 169.233.116.60 ---- Manual Page -- http://www.php.net/manual/en/function.realpath.php Edit -- https://master.php.net/note/edit/78567 Del: integrated -- https://master.php.net/note/delete/78567/integrated Del: useless -- https://master.php.net/note/delete/78567/useless Del: bad code -- https://master.php.net/note/delete/78567/bad+code Del: spam -- https://master.php.net/note/delete/78567/spam Del: non-english -- https://master.php.net/note/delete/78567/non-english Del: in docs -- https://master.php.net/note/delete/78567/in+docs Del: other reasons-- https://master.php.net/note/delete/78567 Reject -- https://master.php.net/note/reject/78567 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#131459) next »