To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null.
Paths include the root, the filename, or both. That is, paths can be formed by adding either the root, filename, or both, to a directory.
The scandir() function in PHP is an inbuilt function that is used to return an array of files and directories of the specified directory. The scandir() function lists the files and directories which are present inside a specified path.
You're looking for basename
.
The example from the PHP manual:
<?php
$path = "/home/httpd/html/index.php";
$file = basename($path); // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>
I've done this using the function PATHINFO
which creates an array with the parts of the path for you to use! For example, you can do this:
<?php
$xmlFile = pathinfo('/usr/admin/config/test.xml');
function filePathParts($arg1) {
echo $arg1['dirname'], "\n";
echo $arg1['basename'], "\n";
echo $arg1['extension'], "\n";
echo $arg1['filename'], "\n";
}
filePathParts($xmlFile);
?>
This will return:
/usr/admin/config
test.xml
xml
test
The use of this function has been available since PHP 5.2.0!
Then you can manipulate all the parts as you need. For example, to use the full path, you can do this:
$fullPath = $xmlFile['dirname'] . '/' . $xmlFile['basename'];
There are several ways to get the file name and extension. You can use the following one which is easy to use.
$url = 'http://www.nepaltraveldoor.com/images/trekking/nepal/annapurna-region/Annapurna-region-trekking.jpg';
$file = file_get_contents($url); // To get file
$name = basename($url); // To get file name
$ext = pathinfo($url, PATHINFO_EXTENSION); // To get extension
$name2 =pathinfo($url, PATHINFO_FILENAME); // File name without extension
With SplFileInfo:
SplFileInfo The SplFileInfo class offers a high-level object oriented interface to information for an individual file.
Ref: http://php.net/manual/en/splfileinfo.getfilename.php
$info = new SplFileInfo('/path/to/foo.txt');
var_dump($info->getFilename());
o/p: string(7) "foo.txt"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With