Nate
Nate

Reputation: 28364

How to get extensions for files with data in paths?

I'm writing an image upload script and have whitelisted common image extensions. I need to be able to get the extension of files to determine if they are in the whitelist, but I'm having trouble with some URLs.

Here is an example:

http://pisces.bbystatic.com/image/BestBuy_US/images/products/5512/5512124_ra.jpg;canvasHeight=280;canvasWidth=280

My code:

echo pathinfo($url, PATHINFO_EXTENSION);

Outputs the following:

jpg;canvasHeight=280;canvasWidth=280

DEMO

I could change my code to this, which fixes the problem:

$parts = explode(';', pathinfo($url, PATHINFO_EXTENSION));
echo $parts[0];

DEMO

However, I don't know if that is the best approach to take here (for one thing, because other websites might use different delimiters for data instead of a semicolon);

Is there a better way?

EDIT: It might be worth noting that I tried uploading the image here as a test (using the example URL) and StackOverflow had no trouble uploading it.

Upvotes: 0

Views: 77

Answers (1)

hyubs
hyubs

Reputation: 737

Using pathinfo() only will match cases like http://google.com -> com. Use parse_url first to safely get the URL path, then use pathinfo to get the file extension.

If the URL uses query strings (e.g. ?foo=bar), that code should be enough. But given your example wherein the URL uses some custom format instead of query strings, you can use RegEx to select only the first alphanumeric part of $ext.

$url = 'http://pisces.bbystatic.com/image/BestBuy_US/images/products/5512/5512124_ra.jpg;canvasHeight=280;canvasWidth=280';
$ext = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
if (!empty($ext)) {
    preg_match('/[a-zA-Z0-9]+/', $ext, $matches);
    $ext = $matches[0];
}

echo $ext;

Upvotes: 1

Related Questions