How to get the image type in php
use getimagesize() or exif_imagetype()
// integer - for example: IMAGETYPE_GIF, IMAGETYPE_JPEG etc.
$type = exif_imagetype($_FILES['image']['tmp_name']);
and
$info = getimagesize($_FILES['image']['tmp_name']);
$mime = $info['mime']; // mime-type as string for ex. "image/jpeg" etc.
$width = $info[0]; // width as integer for ex. 512
$height = $info[1]; // height as integer for ex. 384
$type = $info[2]; // same as exif_imagetype
Mind that exif_imagetype
is much faster than getimagesize
. Check documentation for more info.
Get image extension
you can use image_type_to_extension
function with image type returned by getimagesize
:
$info = getimagesize($path);
$extension = image_type_to_extension($info[2]);
How to get image type
<input type="file" accept="image/*" id="snap" name="snap" multiple="no" title="Choose a Image file to upload" />
in you javascript
var input = $('#snap')[0];
if (input.files && input.files[0]) {
var oFile = input.files[0];
var oFile = oFile.size;
var oFileType = oFile.type
//Option 1
// check for image type (jpg and png are allowed)
var rFilter = /^(image\/jpeg|image\/png)$/i;
if (! rFilter.test(oFileType)) {
alert('Please select a valid image file (jpg and png are allowed)');
return;
}
//Option 2
if (!oFile.fileName.match(/\.(jpg|jpeg|png|gif)$/)){
//TODO do your validation for image type then process ajax
}
}
Tutorial Link
JavaScript api doc
PHP get image file type
$_FILES
merely contains the value that the browser/client specified the uploaded file to be. It is an arbitrary, user supplied value. Don't use it for anything except debugging.
getimagesize()
is a function of the gd library and is maintained there. It happens to also do image type detection. The gd library is generally decent enough, but you need to have it installed.
exif_imagetype()
is a function of the PHP exif extension, which does exclusively image type detection. The exif extension needs to be enabled if you want to use this function. It's also decent enough.
Choose either of the latter two, whichever seems more robust to you, offers the better features or is installed on all your systems. It's hard to give a recommendation for one or the other, in my experience they both work fine.
getting image type of remote image in php
You could do
$headers = get_headers( 'http://www.exampledomain.com/images/2?num=1' );
The $headers
variable will then contain something like
Array
(
[0] => HTTP/1.1 200 OK
[1] => Date: Thu, 14 Oct 2010 09:46:18 GMT
[2] => Server: Apache/2.2
[3] => Last-Modified: Sat, 07 Feb 2009 16:31:04 GMT
[4] => ETag: "340011c-3614-46256a9e66200"
[5] => Accept-Ranges: bytes
[6] => Content-Length: 13844
[7] => Vary: User-Agent
[8] => Expires: Thu, 15 Apr 2020 20:00:00 GMT
[9] => Connection: close
[10] => Content-Type: image/png
)
This will tell you whether the resource exists and what content-type (which is not necessarily also the image type) it is.
EDIT as per Pekka's comment, you still might want to determine it's mime-type after downloading. See
- How Can I Check If File Is MP3 Or Image File.
Some of the given approaches work on remote files too, so you can probably skip the get_headers
pre-check altogether. Decide for yourself which one suits your needs.
How to check uploaded file type in PHP
Never use $_FILES..['type']
. The information contained in it is not verified at all, it's a user-defined value. Test the type yourself. For images, exif_imagetype
is usually a good choice:
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$detectedType = exif_imagetype($_FILES['fupload']['tmp_name']);
$error = !in_array($detectedType, $allowedTypes);
Alternatively, the finfo
functions are great, if your server supports them.
Get image type from base64 encoded src string
Well you have basically two options:
- Trust the metadata
- Type check the image source directly
Option 1:
Probably the quicker way because it only involve splitting string, but it may be incorrect.
Something like:
$data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA.';
$pos = strpos($data, ';');
$type = explode(':', substr($data, 0, $pos))[1];
Option 2:
Use getimagesize()
and it's equivalent for string:
$info = getimagesizefromstring(explode(',', base64_decode($data)[1], 2));
// $info['mime']; contains the mimetype
PHP : binary image data, checking the image type
The bits start with:
$JPEG = "\xFF\xD8\xFF"
$GIF = "GIF"
$PNG = "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a"
$BMP = "BM"
$PSD = "8BPS"
$SWF = "FWS"
The other ones I wouldn't know right now, but the big 3 (jpeg,gif,png) usually cover 99%. So, compare the first bytes to those string, and you have your answer.
Related Topics
Php/Apache: PHP Fatal Error: Call to Undefined Function MySQL_Connect()
How to Send Https Posts Using PHP
Alternative for Deprecated PHP Function: Eregi_Replace
Output (Echo/Print) Everything from a PHP Array
Issues Porting PHP/Gd Wrapper to Imagick
How to Make a Select in PHP/MySQL Case Insensitive
What Is Laravel Render() Method For
PHP Foreach() with Arrays Within Arrays
Differencebetween .= and += in PHP
Codeigniter Activerecord: Join Backticking
Understanding PHP "Out of Memory" Error
File Upload PHP $_Files Undefined Index Error