Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
Advertisements
