How to remove the extension and return only the file name in PHP?

In this post, we are going to see how to remove the extension part and then return only the file name in PHP. Here we are going to do it with the simplest way.

The PHP pathinfo() function can return some information about the file as an array. It also returns the file name without extension. Below is the example:

$file_info = pathinfo('logo.png');
echo "<pre>"; print_r($file_info); echo "</pre>";

The code will return the below array:

    [dirname] => .
    [basename] => logo.png
    [extension] => png
    [filename] => logo

We can see that it returns an array that contains several pieces of information about the file. The last array index “filename” contains the name of the file and it doesn’t have any extension. So we can take this array index to get the filename without extension.

How to detect the file extension in PHP?

Display the country flag of visitors in PHP

So below is the code that returns the file extension:

 $file_info = pathinfo('logo.png');
 $filename = $file_info['filename'];
 echo $filename;

The above code simple returns:


It doesn’t contain the extension.

The alternate method of removing file extension and get the file name only:

We can do the same thing in just one line of code:

  echo pathinfo('logo.png')['filename'];

It also returns the file name only:


So we have seen that how easy is it to remove the extension name from a file name and return the file name only.


Leave a Reply

Your email address will not be published. Required fields are marked *