Determine the Parent Directory of a Path in PHP
Written by Cory S.N. LaViska on June 18th, 2008
A PHP function that returns the parent directory of the specified path.
Examples
| Input | Returns |
|---|---|
| /var/www/htdocs/images/ | /var/www/htdocs/ |
| /var/www/htdocs/images | /var/www/htdocs/ |
| /var/www/htdocs/index.php | /var/www/htdocs/ |
| c:\www\files\folder\ | c:\www\files\ |
Notes
- If a single backslash is detected, all slashes are assumed to be backslashes (as on a Windows file system)
- Trailing slash is not required, but will always be returned
- If $convert_backslashes is true, backslashes will be converted to forward slashes
<?php
function parent_directory($path, $convert_backslashes = false) {
// Detect backslashes
if( strstr($path, '\\') ) $backslash = true;
// Convert backslashes to forward slashes
$path = str_replace('\\', '/', $path);
// Add trailing slash if non-existent
if( substr($path, strlen($path) - 1) != '/' ) $path .= '/';
// Determine parent path
$path = substr($path, 0, strlen($path) - 1);
$path = substr( $path, 0, strrpos($path, '/') ) . '/';
// Convert backslashes back
if( !$convert_backslashes && $backslash ) $path = str_replace('/', '\\', $path);
return $path;
}
?>
function parent_directory($path, $convert_backslashes = false) {
// Detect backslashes
if( strstr($path, '\\') ) $backslash = true;
// Convert backslashes to forward slashes
$path = str_replace('\\', '/', $path);
// Add trailing slash if non-existent
if( substr($path, strlen($path) - 1) != '/' ) $path .= '/';
// Determine parent path
$path = substr($path, 0, strlen($path) - 1);
$path = substr( $path, 0, strrpos($path, '/') ) . '/';
// Convert backslashes back
if( !$convert_backslashes && $backslash ) $path = str_replace('/', '\\', $path);
return $path;
}
?>


Comments
#1 Jatinder on Jul 6th, 2008
#2 Cory S.N. LaViska on Jul 7th, 2008
#3 Ben Werdmuller on Jul 25th, 2008