PHP dirname() Tutorial 🎯

beginner
25 min

PHP dirname() Tutorial 🎯

Welcome to our comprehensive guide on the PHP dirname() function! In this tutorial, we'll explore how to use the dirname() function, its purpose, and various examples to help you understand its practical applications. Let's dive right in!

What is dirname()? πŸ“

The dirname() function in PHP returns the path of the directory in which the given file or directory resides. It's a useful function when you need to navigate up one level in the file system hierarchy.

Syntax πŸ’‘

Here's the basic syntax for the dirname() function:

php
string dirname ( string $path )
  • $path: The path of the file or directory for which you want to get the parent directory.

Example 1: Getting the directory of a file πŸ“

Let's consider a simple example: Suppose you have a file named example.php in the following directory structure:

project/ index.php subfolder/ example.php

You can use the dirname() function in index.php to get the path of the directory of example.php:

php
<?php $filePath = 'subfolder/example.php'; echo dirname($filePath); // Outputs: project/subfolder ?>

Example 2: Using dirname() with include() πŸ’‘

The dirname() function can also be useful when including files using the include() function. Here's an example:

php
<?php $path = dirname(__FILE__); include($path . '/example.php'); ?>

In this example, __FILE__ returns the current file's path. By using dirname(), we get the parent directory path, where our example.php file is located.

Quiz πŸ’‘

Question: What does the dirname() function in PHP return?

A: The name of the directory B: The path of the directory C: The name of the file Correct: B Explanation: The dirname() function returns the path of the directory in which the given file or directory resides.

That's all for now! We hope you found this tutorial helpful in understanding the dirname() function in PHP. As you continue learning, remember to practice and experiment with different examples to solidify your understanding. Happy coding! πŸ€–πŸš€