PHP dirname() (original) (raw)

Skip to content

Summary: in this tutorial, you will learn how to use the PHP dirname() function to get the parent directory’s path of a file or directory path.

Introduction to the PHP dirname() function #

The dirname() function accepts a path and returns a parent directory’s path:

dirname ( string <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi><mi>a</mi><mi>t</mi><mi>h</mi><mo separator="true">,</mo><mi>i</mi><mi>n</mi><mi>t</mi></mrow><annotation encoding="application/x-tex">path , int </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">p</span><span class="mord mathnormal">a</span><span class="mord mathnormal">t</span><span class="mord mathnormal">h</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">in</span><span class="mord mathnormal">t</span></span></span></span>levels = 1 ) : stringCode language: PHP (php)

The dirname() function has two parameters:

The dirname() returns the parent directory’s path that is $levels up from the current directory.

Note that you can use both slash (/) and backslash (\) as the directory separator character on Windows and the forward-slash (/) on other environments such as Linux and macOS.

PHP dirname() function example #

The following example uses the dirname() function to get the parent directory’s path:

`<?php

echo '1.' , dirname("/htdocs/public") , PHP_EOL; echo '2.' , dirname("/htdocs/") , PHP_EOL; echo '3.' , dirname(".") , PHP_EOL; echo '4.' , dirname("C:\") , PHP_EOL; echo '5.' , dirname("/htdocs/public/css/dev", 2);`Code language: HTML, XML (xml)

Output:

1./htdocs 2.\ 3.. 4.C:\ 5./htdocs/publicCode language: plaintext (plaintext)

Summary #

Did you find this tutorial useful?