How can I get the name of the image from url?

consider the following is the image path $image_url='http://development/rwc/wp-content/themes/Irvine/images/attorney1.png'; from this url to get image name with extention use following function basename(); look following code

code:

$image_url='http://development/rwc/wp-content/themes/Irvine/images/attorney1.png';
echo basename($image_url);

output: attorney1.png


Use pathinfo


Sometime url has additional parameters appended to it. In such scenario we can remove the parameter section first and then we can use the PHP's inbuilt pathinfo() function to get the image name from the url.

$url = 'http://images.fitnessmagazine.mdpcdn.com/sites/story/shutterstock_65560759.jpg?itok=b8HiA95H';

Check if the image url has parameters appended.

if (strpos($url, '?') !== false) {
    $t = explode('?',$url);
    $url = $t[0];            
}      

The resulting url variable now contain

http://images.fitnessmagazine.mdpcdn.com/sites/story/shutterstock_65560759.jpg

Use the pathinfo() to retrieve the desired details.

$pathinfo = pathinfo($url);
echo $pathinfo['filename'].'.'.$pathinfo['extension'];

This will give shutterstock_65560759.jpg as output.

Tags:

Php

Curl