PHP basename() Tutorial 🎯

beginner
25 min

PHP basename() Tutorial 🎯

Welcome to the PHP basename() tutorial! In this lesson, we'll explore the basename() function, one of the essential PHP string functions that helps you work with file paths. By the end of this tutorial, you'll be able to extract file names from various path formats and understand when to use basename(). Let's dive in!

What is PHP basename()? πŸ“

The basename() function is used to extract the base name (file name) from a given path. This function is particularly useful when working with directories, files, or URLs containing directories and files.

php
basename(string $path): string

In the above function signature, $path is the path of the file or directory you want to extract the base name from. The function returns the base name as a string.

Practical Examples πŸ’‘

Example 1: Extracting the base name from a simple file path

php
$path = "/example/documents/file.txt"; $filename = basename($path); echo $filename; // Output: file.txt

In the above example, we have a file path "/example/documents/file.txt", and we're extracting the base name using basename(). The output will be "file.txt".

Example 2: Extracting the base name from a URL

php
$url = "https://www.codeyourcraft.com/example/file.html"; $filename = basename($url); echo $filename; // Output: file.html

In this example, we're extracting the base name from a URL, which contains a directory ("example") and a file extension (.html). The output will be "file.html".

Advanced Usage πŸ’‘

Removing File Extension

You can use basename() in combination with the pathinfo() function to remove the file extension:

php
$path = "/example/documents/file.txt"; $path_info = pathinfo($path); $filename = $path_info['filename']; echo $filename; // Output: file

In this example, we're using pathinfo() to get an associative array containing information about the path, such as the directory, extension, and base name. Then, we're extracting the base name ("file") from the array.

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What does the PHP `basename()` function do?

That's all for today's PHP basename() tutorial! Keep practicing and stay tuned for more in-depth PHP lessons on CodeYourCraft. Happy coding! πŸ’»πŸŽ‰