PHP check if file is an image
Native way to get the mimetype:
For PHP < 5.3 use mime_content_type()
For PHP >= 5.3 use finfo_open() or mime_content_type()
Alternatives to get the MimeType are exif_imagetype and getimagesize, but these rely on having the appropriate libs installed. In addition, they will likely just return image mimetypes, instead of the whole list given in magic.mime.
While mime_content_type
is available from PHP 4.3 and is part of the FileInfo extension (which is enabled by default since PHP 5.3, except for Windows platforms, where it must be enabled manually, for details see here).
If you don't want to bother about what is available on your system, just wrap all four functions into a proxy method that delegates the function call to whatever is available, e.g.
function getMimeType($filename)
{
$mimetype = false;
if(function_exists('finfo_open')) {
// open with FileInfo
} elseif(function_exists('getimagesize')) {
// open with GD
} elseif(function_exists('exif_imagetype')) {
// open with EXIF
} elseif(function_exists('mime_content_type')) {
$mimetype = mime_content_type($filename);
}
return $mimetype;
}
PHP, HTML check if file is an image
So the checking file type by name or extension is not good, because you can easily change it by plain remane function. You can check if uploaded file is an image using e.g. mime type. In php you have function mime_content_type()
. Example of usage:
$imageMimeTypes = array(
'image/png',
'image/gif',
'image/jpeg');
$fileMimeType = mime_content_type($_FILES['UPLFILE2']['tmp_name']);
if (in_array($fileMimeType, $imageMimeTypes)) {
//passed validation
}
Of course you can define more mime types of images.
PHP: How to check if image file exists?
You need the filename in quotation marks at least (as string):
if (file_exists('http://www.mydomain.com/images/'.$filename)) {
… }
Also, make sure $filename
is properly validated. And then, it will only work when allow_url_fopen
is activated in your PHP config
Check if file is image or pdf
I like this approach it saves a bit of typing
return (in_array($file['content-type'], ['image/jpg', 'application/pdf']));
php file upload check if file is an image
May be it will help you,
if(!empty($_FILES['img'])) {
$img = $_FILES['img'];
foreach($img['name'] as $key => $name) {
$type = $img['type'][ $key ];
$type = strtolower($type);
if($type == 'image/jpg' || $type == 'image/jpeg' || $type == 'image/png' || $type == 'image/gif'){
$newname = date('YmdHis',time()).mt_rand().'.jpg';
$stmt = $conn->prepare("INSERT INTO gallery (imgsrc, title, description) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $newname, $_POST['imgtitle'], $_POST['imgdesc']);
if($stmt->execute()) {
move_uploaded_file($img['tmp_name'][ $key ],'../../images/'.$newname);
}
}
}
header("location: ../");
}
How to check if image file inputed or not in PHP?
Replace this part of your PHP code
if(!empty($_FILES['profile_image'])){
#then execute this code when there is image uploaded
}else{
#execute this
}
with this
if (is_uploaded_file($_FILES ['profile_image'] ['tmp_name'])) {
#then execute this code when there is image uploaded
} else {
#execute this
}
And this part of your HTML code
<form method='POST' action='update.PHP'>
with this
<form method='POST' action='update.PHP' enctype='multipart/form-data'>
the most reliable way to check upload file is an image
finfo_*
library would be good but it will work with >= 5.3.0
versions,
AND getimagesize()
GD
library function that is return image info WxH
and size
if image invalid then getimagesize()
show warning so better to use to validate image using finfo_*
function,
you can also do for cross version code, see below sample code
<?php
$file = $_FILES['photo'];
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
$error = null;
if(function_exists('finfo_open')){ //(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
if (!in_array(finfo_file($fileinfo, $file['tmp_name']), $whitelist_type)) {
$error[] = "Uploaded file is not a valid image";
}
}else if(function_exists('mime_content_type')){ //supported (PHP 4 >= 4.3.0, PHP 5)
if (!in_array(mime_content_type($file['tmp_name']), $whitelist_type)) {
$error[] = "Uploaded file is not a valid image";
}
}else{
if (!@getimagesize($file['tmp_name'])) { //@ - for hide warning when image not valid
$error[] = "Uploaded file is not a valid image";
}
}
Related Topics
PHP Pdo: Get the Columns Name of a Table
Manipulate a String That Is 30 Million Characters Long
PHP Class Instantiation. to Use or Not to Use the Parentheses
PHP Mail() Function on Localhost
.Htaccess Rewrite Get Variables
PHP MySQLi Prevent SQL Injection
Is There a PHP Library For Email Address Validation
PHP: Merge 2 Multidimensional Arrays
How to Loop Through a MySQL Result Set
Simple Postgresql Statement - Column Name Does Not Exists
Can HTML Be Embedded Inside PHP "If" Statement
Fetching Data from MySQL Database to HTML Dropdown List
Extract Jsonp Resultset in PHP
Socket Transport "Ssl" in PHP Not Enabled