Get file name from a path in PHP

78

Today, we will learn how to get the file name from a given path in PHP. There are various ways to achieve this, but we will discuss two common methods in detail. Let’s assume that we have a database that stores filename along with the path in the table.

Suppose, we have a file path like storage/upload/image/hydrating-fruits.jpg that is stored in the database. So, how can we get the name of the file e.g. hydrating-fruits.jpg? Well, we can do this using regex but PHP provides simple functions that can be easy to implement.

The two methods we will use in this article are:

  • pathinfo() function
  • basename() function

Method 1: Using pathinfo() function

The pathinfo() is a PHP function that returns information about a file path. The pathinfo() returns information about path: either an associative array or a string, depending on flags.

Syntax:

pathinfo(string $path, int $flags = PATHINFO_ALL): array|string

Here, $path is the path o be parsed and $flag specifies a specific element to be returned; one of PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION or PATHINFO_FILENAME.

For the file path that is stored in the database, we will first retrieve all the information about the file as accessed the key accordingly.

<?php

$file_info = pathinfo('storage/upload/image/hydrating-fruits.jpg'); 

var_dump($file_info);


It will give below output. From this array, we can access the file name using the basename index.

pathinfo() function output

Method 2: Using basename() function

As an alternative to the above function, we can use basename()function to directly access the file name from the file path. It returns the trailing name component of the path.

//Syntax
basename(string $path, string $suffix = "")

This function accepts two parameters i.e. path and suffix. The path is the file path whereas suffixwhich is optional, if the name component ends in suffix this will also be cut off.

The below example shows how we can access only filename from the file path directory in PHP.

<?php

$filename = basename('storage/upload/image/hydrating-fruits.jpg'); 
$without_ext = basename('storage/upload/image/hydrating-fruits.jpg', '.jpg')

var_dump($filename);
var_dump($without_ext);

// output
hydrating-fruits.jpg    <-- with extension
hydrating-fruits    <-- without extension

This is all about getting file names from the file path in PHP. This is a common function that can become handy when dealing with files and directories.

Read More Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.