Created
August 5, 2013 09:17
-
-
Save umidjons/6154548 to your computer and use it in GitHub Desktop.
realpath() alternative to detect absolute path (URN and URL is not supported, only local paths on the server)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * This function is to replace PHP's extremely buggy realpath(). | |
| * @param string The original path, can be relative etc. | |
| * @return string The resolved path, it might not exist. | |
| */ | |
| public static function truepath( $path ) | |
| { | |
| // whether $path is unix or not | |
| $unipath = strlen( $path ) == 0 || $path{0} != '/'; | |
| // attempts to detect if path is relative in which case, add cwd | |
| if ( strpos( $path, ':' ) === false && $unipath ) | |
| $path = getcwd() . DIRECTORY_SEPARATOR . $path; | |
| // resolve path parts (single dot, double dot and double delimiters) | |
| $path = str_replace( array( '/', '\\' ), DIRECTORY_SEPARATOR, $path ); | |
| $parts = array_filter( explode( DIRECTORY_SEPARATOR, $path ), 'strlen' ); | |
| $absolutes = array(); | |
| foreach ( $parts as $part ) { | |
| if ( '.' == $part ) continue; | |
| if ( '..' == $part ) { | |
| array_pop( $absolutes ); | |
| } else { | |
| $absolutes[ ] = $part; | |
| } | |
| } | |
| $path = implode( DIRECTORY_SEPARATOR, $absolutes ); | |
| // resolve any symlinks | |
| if ( file_exists( $path ) && linkinfo( $path ) > 0 ) $path = readlink( $path ); | |
| // put initial separator that could have been lost | |
| $path = !$unipath ? '/' . $path : $path; | |
| return $path; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @umidjons! I really like what you've done here as I find
realpath()often doesn't work well for projects that I work on. Nice work!Would you consider providing an open-source license for this gist? I am working on a free software neuroimaging project and we are looking for a solution like this.
Please feel free to contact me via the email listed on my profile if so.