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?
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:
pathinfo($sourceFile, PATHINFO_EXTENSION);// should work nowgetimagesize()returns a constant indicating the image type in the second indexKeep in mind that
exif_imagetype()returns exactly the same information as the second index ofgetimagesize(), if you have access to this function it should perform way better.Now for the image constants, the most common three are:
Checking is as simple as doing something like this:
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.