Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use PHP to Get File Path/Extension from URL string [duplicate]

Tags:

file

php

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.

like image 623
chris Avatar asked May 16 '13 08:05

chris


1 Answers

$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);
like image 139
gotjosh Avatar answered Oct 16 '22 08:10

gotjosh