PHP Remove parameters from image extension

与世无争的帅哥 提交于 2019-12-13 05:13:21

问题


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;
?>

回答1:


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);
}



回答2:


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.



来源:https://stackoverflow.com/questions/22016888/php-remove-parameters-from-image-extension

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!