2

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;
?>
Kara
  • 6,115
  • 16
  • 50
  • 57
user3350854
  • 55
  • 1
  • 1
  • 6

2 Answers2

5

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);
}
Community
  • 1
  • 1
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
0

Don't be that fixed about the term "file name extension". It is a relict from the 80th and overrated. File handling and usage should not depend on those name rules on a modern system. (I know it still does on MS-Windows based systems, but that does not invalidate the truth of the statement)

In your specific case you actually face another problem: it looks like you setup your http server such that it directly tries to deliver a physical file from the local file system. That is not how such url requests are meant to be handled. Instead they should be handled by some script handler that is able to interpret the additional parameters, apply any filters requested and deliver the result of that action.

If you really want to handle this strictly string based and since you appear to be using php, then take a look at the parse_url() function to extract single parts from the url.

arkascha
  • 41,620
  • 7
  • 58
  • 90