Not able to get image file extension

2019-08-15 03:29发布

问题:

I'm using Uploadify to upload an image to the server.
The image is uploaded, and placed in the temp folder of the web server.

Now I need to work with the file beore moving it to it's real location, and I have the following code:

// Get the filepath and filename from server temp dir
$sourceFile   = $_FILES[ 'Filedata' ][ 'tmp_name' ]; // e.g. c:\server\path\tmp\php159.tmp

// Solution 1 for getting file extension
$fileExt1     = pathinfo($sourceFile, PATHINFO_EXTENSION); // <-- This only returns .tmp

// Solution 2 with getimagesize
list(,,$extension) = getimagesize($sourceFile);
$fileExt2     = $extension; // this only returns the number 2.

// Solution 3 with getimagesize
$img = getimagesize($sourceFile);
$fileExt3 = $img[2]; // this only returns the number 2.

I'm not using regex to read filename, because a user may name the file anything, so I have to read file data.

Any sugegstions anyone?

回答1:

Well, first off $sourceFile should be $_FILES['Filedata']['name'] instead of $_FILES['Filedata']['tmp_name'] but only for your first solution.

Now regarding your solutions/problems:

  1. pathinfo($sourceFile, PATHINFO_EXTENSION); // should work now
  2. getimagesize() returns a constant indicating the image type in the second index
  3. same as point 2

Keep in mind that exif_imagetype() returns exactly the same information as the second index of getimagesize(), if you have access to this function it should perform way better.

Now for the image constants, the most common three are:

  • IMAGETYPE_GIF = 1
  • IMAGETYPE_JPEG = 2
  • IMAGETYPE_PNG = 3

Checking is as simple as doing something like this:

switch (exif_imagetype($_FILES['Filedata']['tmp_name']))
{
    case IMAGETYPE_GIF:
        echo 'is a GIF';
    break;

    case IMAGETYPE_JPEG:
        echo 'is a JPEG';
    break;

    case IMAGETYPE_PNG:
        echo 'is a PNG';
    break;

    case default:
        echo 'is something else;
    break;
}

One more thing, it's better to use getimagesize() / exif_imagetype() than to rely on the file extension, since the extension can be easily changed.



回答2:

Your solutions #2 and #3 both work already. From the getimagesize() manual page:

Returns an array with 7 elements.
...
Index 2 is one of the IMAGETYPE_XXX constants indicating the type of the image.

So for a .gif then this should be the integer 2. To get the file extension use image_type_to_extension() since you already are using the gd library. eg.

$img = getimagesize($sourceFile);
$fileExt = image_type_to_extension($img[2])


回答3:

exif_imagetype() can determine a number of graphics formats, is fast and doesn't even use GD.

Edit: I see you are already using getimagesize() and have trouble translating the constants. The exif_imagetype() page linked above has a translation of all returned image types that should be valid for getimagesize() as well.