How can i get image name and image extension from image url

Viewed 609

I have a image url with query strings. I just want to get image name and its extension in php.

https://static01.nyt.com/images/2018/08/28/us/28vote_print/28vote_xp-articleLarge.jpg?quality=75&auto=webp&disable=upscale
4 Answers

You can use pathinfo() and parse_url():

$url = 'https://static01.nyt.com/images/2018/08/28/us/28vote_print/28vote_xp-articleLarge.jpg?quality=75&auto=webp&disable=upscale';

// Getting the name
$name = pathinfo(parse_url($url)['path'], PATHINFO_FILENAME);

// Getting the extension
$ext = pathinfo(parse_url($url)['path'], PATHINFO_EXTENSION);

// Output:
var_dump($name);    // 28vote_xp-articleLarge
var_dump($ext);     // jpg

use php pathinfo() function to get the details http://www.php.net/manual/en/function.pathinfo.php

$fileParts = pathinfo("https://static01.nyt.com/images/2018/08/28/us/28vote_print/28vote_xp-articleLarge.jpg?quality=75&auto=webp&disable=upscale");
echo"<pre>";    
print_r($fileParts);
$extension=explode("?",$fileParts ['extension'])[0];

Output

Array
(
    [dirname] => https://static01.nyt.com/images/2018/08/28/us/28vote_print
    [basename] => 28vote_xp-articleLarge.jpg?quality=75&auto=webp&disable=upscale
    [extension] => jpg?quality=75&auto=webp&disable=upscale
    [filename] => 28vote_xp-articleLarge
)

I think you look like as below

$explode_url=explode(".",$img_url);
        $end_typ = end($explode_url);
        $get_imgtyp=explode("?",$end_typ);
        $new_imgName=md5(time().'image').".".$get_imgtyp[0];
Related