Skip to content

Instantly share code, notes, and snippets.

@userlond
Forked from ohaal/find_relative_path.func.php
Last active February 3, 2016 11:51
Show Gist options
  • Save userlond/43a3a76756d4b1604b62 to your computer and use it in GitHub Desktop.
Save userlond/43a3a76756d4b1604b62 to your computer and use it in GitHub Desktop.
Find the relative path between two paths
<?php
/**
*
* Find the relative file system path between two file system paths
*
* @param string $frompath Path to start from
* @param string $topath Path we want to end up in
*
* @return string Path leading from $frompath to $topath
*/
function find_relative_path ( $frompath, $topath ) {
$from = explode( DIRECTORY_SEPARATOR, $frompath ); // Folders/File
$to = explode( DIRECTORY_SEPARATOR, $topath ); // Folders/File
$relpath = '';
$i = 0;
// Find how far the path is the same
while ( isset($from[$i]) && isset($to[$i]) ) {
if ( $from[$i] != $to[$i] ) break;
$i++;
}
$j = count( $from ) - 1;
// Add '..' until the path is the same
while ( $i <= $j ) {
if ( !empty($from[$j]) ) $relpath .= '..'.DIRECTORY_SEPARATOR;
$j--;
}
// Go to folder from where it starts differing
while ( isset($to[$i]) ) {
if ( !empty($to[$i]) ) $relpath .= $to[$i].DIRECTORY_SEPARATOR;
$i++;
}
// Strip last separator
return substr($relpath, 0, -1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment