PHP dirname() Function

Code Snippets Dirname


In this code snippet, we’ll learn about the dirname() function in PHP.

The dirname() function takes in a path string and gives you the parent directory of it. A second parameter can be added where you can specify how many levels up you want to go.

Let’s see the example code below.



//__FILE__ contains the path of the current file.
$filePath = __FILE__;

echo "Current file path: " . $filePath;
echo "<br>";

//Gets the path of the parent directory.
echo "Parent dir. file path: " . dirname($filePath);
echo "<br>";

//You can use the last parameter to specify how many levels up you want to go. 
echo "Parent of parent dir. file path: " . dirname($filePath, 2);
echo "<br>";

Resulting Output:


Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger