Home » Php » Use PHP to Get File Path/Extension from URL string

Use PHP to Get File Path/Extension from URL string

Posted by: admin July 12, 2020 Leave a comment


I’m reading up on pathinfo basename and the like. But all I am gathering from those are how to obtain the details I want when using an absolute/relative path. What I am trying to figure out is how can I get the filename.ext from a url string (not necessarily the active URL, maybe a user input url).

Currently I am looking to get the file name and extension of user provided URLs containing images. But may want to extend this further down the road. So in all I would like to figure out how I can get the filename and extension

I thought about trying to use some preg_match logic finding the last / in the url, spliting it, finding the ? from that (if any) and removing the point beyond that and then trying to sort it out after with whats left. but I get stuck in cases where the file has multiple . in the name ie: 2012.01.01-name.jpg

So I am looking for a sane optimal way of doing this without to much margin of error.

How to&Answers:

use parse_url($url, PHP_URL_PATH) to get URI and use URI in pathinfo/basename.


$path      = parse_url($url, PHP_URL_PATH);       // get path from url
$extension = pathinfo($path, PATHINFO_EXTENSION); // get ext from path
$filename  = pathinfo($path, PATHINFO_FILENAME);  // get name from path

Also possible with one-liners:

$extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
$filename  = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_FILENAME);


You can use the below code to do what you want…

$fileName = $_SERVER['SCRIPT_FILENAME']; //$_SERVER['SCRIPT_FILENAME'] can be replaced by the variable in which the file name is being stored
$fileName_arr = explode(".",$fileName);

$arrLength = count($fileName_arr);
$lastEle = $arrLength - 1;
echo $fileExt = $fileName_arr[$arrLength - 1]; //Gives the file extension
$fileNameMinusExt = implode(".",$fileName_arr);

$fileNameMinusExt_arr = explode("/",$fileNameMinusExt);
$arrLength = count($fileNameMinusExt_arr);
$lastEle = $arrLength - 1;
echo $fileExt = $fileNameMinusExt_arr[$arrLength - 1]; //Gives the filename