How to get file name from a path in PHP?

In PHP, you can extract the file name from a file path using several built-in functions. The most common approaches are using pathinfo() and basename() functions.

Using pathinfo()

The pathinfo() function returns an array containing information about a file path ?

<?php
    $file = pathinfo('/home/cg/root/6985034/main.php');
    echo $file['basename'], "<br>";
?>
main.php

Using basename()

The basename() function extracts the filename from a path. You can optionally specify a suffix to remove ?

<?php
    $path = "/home/cg/root/6985034/main.php";
    $file = basename($path, ".php");
    echo $file;
?>
main

Comparison

Function Returns Can Remove Extension
pathinfo() Array with detailed path info Access via ['filename'] key
basename() String filename Yes (with second parameter)

Conclusion

Use basename() for simple filename extraction and pathinfo() when you need detailed path information. Both functions work with various path formats and are safe for file path manipulation.

Updated on: 2026-03-15T08:23:06+05:30

930 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements