Skip to content
Advertisement

PHP Remove parameters from image extension

I am getting the image url from one function. I need to find the extension for the image. Sometimes the image url comes with parameters like http://slimages.macys.com/is/image/MCY/products/4/optimized/1776484_fpx.tif?$filterlrg$&wid=370. So, the file extension comes like tif?$filterlrg$&wid=370. How can I get the exact extension.

Below is my code

<?php
    $srcimg = 'http://slimages.macys.com/is/image/MCY/products/4/optimized/1776484_fpx.tif?$filterlrg$&wid=370';
    $fullpath = basename($srcimg);
    $userImageDetails = pathinfo($fullpath);
    $extension = strtolower($userImageDetails['extension']);
    echo $extension;
?>

Advertisement

Answer

You can use parse_url(), as suggested in this answer

$link = 'http://slimages.macys.com/is/image/MCY/products/4/optimized/1776484_fpx.tif?$filterlrg$&wid=370';

if ($url = parse_url($link)) { 
   echo pathinfo($url['path'], PATHINFO_EXTENSION);
}

output

tif

with no second argument, parse_url returns an associative array but if you only want the path, you can pass a second argument parse_url($link, PHP_URL_PATH) and it will return a single variable instead.

if ($path = parse_url($link, PHP_URL_PATH)) { 
   echo pathinfo($path, PATHINFO_EXTENSION);
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement