Ima开发者_开发知识库gine I have some file data in a variable $data
.
I need to determine whether it is an image or not.
No need for details such as corrupt images etc.
First thought would be getting the file mime type by looking at the magic number and then see whether "image" is in the mime type.
No such luck, even if I have a "file extension to mime type" script, I don't have a reliable way to get mime from magic number.
My next option was to have a reasonable list of image file magic numbers and consult them. However, it is relatively difficult to find such magic numbers (gif for instance has different magic numbers, some of which could pretty rare - if memory serves me right).
A better idea would be some linux program which can do this kind of thing.
Any ideas? I'm running RHEL and PHP 5.3. I've got root access - ie able to install stuff if needed.
- Chris.
The best answer (which I've determined from Col. Shrapnel) would be the use of:
$handle = imagecreatefromstring($data);
Quoting the PHP manual:
An image resource will be returned on success. FALSE is returned if the image type is unsupported, the data is not in a recognised format, or the image is corrupt and cannot be loaded.
The standard file
utility might be what you're looking for. It uses a table of magic numbers to identify the file format:
$ file test.jpg
test.jpg: JPEG image data, JFIF standard 1.01
If you don't wish to create a temporary file, you can use file -
and pipe the data into its stdin. Make sure you watch for the termination of the child process, because file
will write its output and stop as soon as it has read enough of your stream to be certain of the format.
There also was finfo: http://php.net/manual/en/function.finfo-open.php Lots of working code on this php.net manual page.
Additionally you can check first 3-bytes of your data stream, there should be image file header data which identifies image file format.
If I were you I'd avoid using the imagecreatefromstring
solution if you only need to determine if it is an image because this would use additional memory when creating the image resource. Also it would only support JPEG, PNG, GIF, WBMP, and GD2. while other equally valid image formats would not be valid, eg. ICO.
I would use finfo as suggested or if you don't have the PECL extensions, I'd recommend file -bi image...
. As it would return the content-type, eg. image/png
. You can just check if it starts with image/*
. This way your script would accept any image format.
I think standard getimagesize() is enough.
Of course it require a file, bit it isn't a big deal.
精彩评论