Use PHP to get file path / extension from URL string

I read pathinfo basename and the like. But all I collect is how to get the details I want using the absolute / relative path. I am trying to figure out how I can get filename.ext from the url string (optional active url, maybe user url).

I'm currently looking to get the file name and extension of user-provided URLs containing images. But you might want to expand it further down the road. Thus, in everything I would like to find out how I can get the file name and extension

I was thinking of trying to use some preg_match logic to find the last / in the url, split it, find it? from this (if any) and remove the point outside it, and then try to figure it out after what remains. but I get stuck in cases where the file has several . in the name, 2012.01.01-name.jpg .: 2012.01.01-name.jpg

So, I am looking for a reasonable optimal way to do this without significant errors.

+4
source share
3 answers

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

+12
source
 $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 

It is also possible with one layer:

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

You can use the code below 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 unset($fileName_arr[$lastEle]); $fileNameMinusExt = implode(".",$fileName_arr); $fileNameMinusExt_arr = explode("/",$fileNameMinusExt); $arrLength = count($fileNameMinusExt_arr); $lastEle = $arrLength - 1; echo $fileExt = $fileNameMinusExt_arr[$arrLength - 1]; //Gives the filename 
+1
source

Source: https://habr.com/ru/post/1481114/


All Articles