PHP Uploading Files - Image Only Checking

PHP Uploading files - image only checking

Yes, quite easily. But first off, you need some extra bits:

// never assume the upload succeeded
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['file']['error']);
}

$info = getimagesize($_FILES['file']['tmp_name']);
if ($info === FALSE) {
die("Unable to determine image type of uploaded file");
}

if (($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)) {
die("Not a gif/jpeg/png");
}

Relevant docs: file upload errors, getimagesize and image constants.

How to check whether the user uploaded a file in PHP?

You can use is_uploaded_file():

if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
echo 'No upload';
}

From the docs:

Returns TRUE if the file named by
filename was uploaded via HTTP POST.
This is useful to help ensure that a
malicious user hasn't tried to trick
the script into working on files upon
which it should not be working--for
instance, /etc/passwd.

This sort of check is especially
important if there is any chance that
anything done with uploaded files
could reveal their contents to the
user, or even to other users on the
same system.

EDIT: I'm using this in my FileUpload class, in case it helps:

public function fileUploaded()
{
if(empty($_FILES)) {
return false;
}
$this->file = $_FILES[$this->formField];
if(!file_exists($this->file['tmp_name']) || !is_uploaded_file($this->file['tmp_name'])){
$this->errors['FileNotExists'] = true;
return false;
}
return true;
}

Check if image has been selected for upload

Use is_uploaded_file() function to check if the user has uploaded any file or not, and then process inputs accordingly, like this:

if(is_uploaded_file($_FILES['files']['tmp_name'][0])){
// user has uploaded a file
}else{
// user hasn't uploaded anything
}

Above solution code is based on your name attribute of input tag,

<input ... name="files[]" ... />

If it was <input ... name="files" ... /> then the if condition would be like this:

if(is_uploaded_file($_FILES['files']['tmp_name'])){
...
}else{
...
}

Sidenote: Use var_dump($_FILES); to see the complete array structure.

PHP Upload Image formats only?

Based on this answer

if($_POST[add]){

$file_type = $_FILES['image']['type']; //returns the mimetype

$allowed = array("image/jpeg", "image/gif", "image/png");
if(!in_array($file_type, $allowed)) {
$error_message = 'Only jpg, gif, and png files are allowed.';

echo $error_message;

exit();

}

$dataType = $_POST["dataType"];

... rest of your code below

Footnotes:

  • Other Internet media types should you want to use them in the future.

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";
}
}

PHP check if there is a file selected for upload

Use the $_FILES array and the UPLOAD_ERR_NO_FILE constant:

if(!isset($_FILES['file_upload']) || $_FILES['file_upload']['error'] == UPLOAD_ERR_NO_FILE) {
echo "Error no file selected";
} else {
print_r($_FILES);
}

You can also check UPLOAD_ERR_OK which indicates if the file was successfully uploaded (present and no errors).

Note: you cannot use empty() on the $_FILES['file_upoad'] array, because even if no file is uploaded, the array is still populated and the error element is set, which means empty() will return false.

Check picture file type and size before file upload in php

Note that you might not want to rely on file extensions to determine file type. It would be rather easy for someone to upload an executable file with a .png extension for example. A mime-type can also easily be forged by a malicious client to pass as an image. Relying on that information is a security risk.

PHP Documentation:

The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.

Try loading the images with gd (getimagesize()) to make sure they are actually valid images (and not just random files pretended with the header of an image file... finfo_file relies on those headers).

if($_FILES["imagefile"]["size"] >= 2120000) {
echo "F2";
die();
} else {
$imageData = @getimagesize($_FILES["imagefile"]["tmp_name"]);

if($imageData === FALSE || !($imageData[2] == IMAGETYPE_GIF || $imageData[2] == IMAGETYPE_JPEG || $imageData[2] == IMAGETYPE_PNG)) {
echo "F2";
die();
}
}

If you really must use the extension to verify if the file is an image, use strtolower() to put the extension into lowercase.

$filecheck = basename($_FILES['imagefile']['name']);
$ext = strtolower(substr($filecheck, strrpos($filecheck, '.') + 1));

if (!(($ext == "jpg" || $ext == "gif" || $ext == "png") && ($_FILES["imagefile"]["type"] == "image/jpeg" || $_FILES["imagefile"]["type"] == "image/gif" || $_FILES["imagefile"]["type"] == "image/png") &&
($_FILES["imagefile"]["size"] < 2120000))){
echo "F2";
die();
}


Related Topics



Leave a reply



Submit