Determine the Parent Directory of a Path in PHP

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

<?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;
}
?>

Comments

Why don't you simply use PHP's inbuilt dirname() function?

#1 Jatinder on Jul 6th, 2008

@Jatinder: dirname() doesn't return the parent directory. From the PHP Manual, "Given a string containing a path to a file, this function will return the name of the directory."

#2 Cory S.N. LaViska on Jul 7th, 2008

@Cory It returns the path of the directory. You can nest calls to it, so dirname(dirname($filepath)) will return the full path of the parent directory.

I use this a lot for relative paths to the current file - i.e. dirname(dirname(__FILE__))

#3 Ben Werdmuller on Jul 25th, 2008

Add a comment

Name*

Email*

Never, ever sold or spammed :)

Homepage

Comment*

Sorry, plain text only :(