Validate that a file is a picture in PHP

Asked
Active3 hr before
Viewed126 times

9 Answers

90%

Header check is not enough for checking the validity of an image file. PHP Documentation clearly expresses that you shouldn't use getimagesize to check that a given file is a valid image. See https://www.php.net/manual/en/function.getimagesize.php,The most efficient way would be to look at the beginning bytes of the file and test for 'magic number' file specifier. Here is a list of magic numbers.,If a file is uploaded to the server, is there a way using PHP, to make sure that it's actually a picture and not just a file with a .jpg or .gif extension?, 3 Oh and I believe that a large number of the users of this site do not have CS degrees. Most people end up here from Google who are trying to learn something about the language they are learning. – snicker Oct 19 '09 at 13:48

array getimagesize(string $filename[, array & $imageinfo])
load more v
88%

PHP Image Upload with Size Type Dimension Validation,In PHP, we validate the file type, size and dimension before uploading.  The uploaded file data like name size, temporary target are in $_FILES[“image_file”] array. PHP move_uploaded_file function is used to upload the file by accessing file data stored in $_FILES superglobal.,The server-side image file validation takes place in the following aspects.,The following screenshots showing the success and failure cases while executing PHP image upload with validation example.

This form contains file input to allow the user to choose files to be uploaded. On submitting this form, the file data is sent to the PHP to upload it to the target after validation.

<h2>PHP Image Upload with Size Type Dimension Validation</h2>
<form id="frm-image-upload" action="index.php" name='img' method="post"
    enctype="multipart/form-data">
    <div class="form-row">
        <div>Choose Image file:</div>
        <div>
            <input type="file" class="file-input" name="file-input">
        </div>
    </div>

    <div class="button-row">
        <input type="submit" id="btn-submit" name="upload"
            value="Upload">
    </div>
</form>
<?php if(!empty($response)) { ?>
<div class="response <?php echo $response["type"]; ?>
    ">
    <?php echo $response["message"]; ?>
</div>
<?php }?>
load more v
72%

What is 'CodeProject'?, help? What is 'CodeProject'? General FAQ Ask a Question Bugs and Suggestions Article Help Forum About Us ,Read the question carefully.,View Python questions

< ? php
if (isset($_POST['save'])) {

   //Validate image
   if (empty($_POST["image"])) {
      $imageError = "";
   } else {
      $image = check_input($_POST["image"]);
      $allowed = array('jpeg', 'jpg', "png", "gif", "bmp", "JPEG", "JPG", "PNG", "GIF", "BMP");
      $ext = pathinfo($image, PATHINFO_EXTENSION);
      if (!in_array($ext, $allowed)) {
         $imageError = "jpeg only";
      }
   }

}

// Validate data
function check_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
} <
?
load more v
65%

here is the code I tried, to validate the uploaded image files.,Now let’s try something to check if the given image is valid, but before going into the example, let me tell you, even the following functions in PHP will not validate an image correctly.,Thanks. Would be great if PHP team do something more sophisticated to validate imagens,and used the following PHP code to check the validity of the image, you can see I have tried the four commonly recommended PHP functions to check if the given image is valid and each one of them failed.

Check if uploaded image is valid with getimagesize( ) in PHP

$imagesizedata = getimagesize($file);
if ($imagesizedata) {
   //do something
}
load more v
75%

index.php

<html>
<br /><br />

<body style="text-align: center;">
   <h2>PHP image upload file size and file type validation</h2>
   <form action="process.php" metod="post" enctype="multipart/form-data">
      Images ( JPG, PNG, GIF, JPEG ): <br /><br />
      <input type="file" name="images" /><br /><br />
      <input type="submit" value="UPLOAD">
   </form>
</body>

</html>
load more v
40%

Handling file uploads , Command line usage ,Uploading multiple files

You 'd better check $_FILES structure and values throughly.The following code cannot cause any errors absolutely.Example:<?phpheader('
Content - Type: text / plain;
charset = utf - 8 ');try {        // Undefined | Multiple Files | $_FILES Corruption Attack    // If this request falls under any of them, treat it invalid.    if (        !isset($_FILES['
upfile ']['
error ']) ||        is_array($_FILES['
upfile ']['
error '])    ) {        throw new RuntimeException('
Invalid parameters.
');    }    // Check $_FILES['
upfile ']['
error '] value.    switch ($_FILES['
upfile ']['
error ']) {        case UPLOAD_ERR_OK:            break;        case UPLOAD_ERR_NO_FILE:            throw new RuntimeException('
No file sent.
');        case UPLOAD_ERR_INI_SIZE:        case UPLOAD_ERR_FORM_SIZE:            throw new RuntimeException('
Exceeded filesize limit.
');        default:            throw new RuntimeException('
Unknown errors.
');    }    // You should also check filesize here.     if ($_FILES['
upfile ']['
size '] > 1000000) {        throw new RuntimeException('
Exceeded filesize limit.
');    }    // DO NOT TRUST $_FILES['
upfile ']['
mime '] VALUE !!    // Check MIME Type by yourself.    $finfo = new finfo(FILEINFO_MIME_TYPE);    if (false === $ext = array_search(        $finfo->file($_FILES['
upfile ']['
tmp_name ']),        array(            '
jpg ' => '
image / jpeg ',            '
png ' => '
image / png ',            '
gif ' => '
image / gif ',        ),        true    )) {        throw new RuntimeException('
Invalid file format.
');    }    // You should name it uniquely.    // DO NOT USE $_FILES['
upfile ']['
name '] WITHOUT ANY VALIDATION !!    // On this example, obtain safe unique name from its binary data.    if (!move_uploaded_file(        $_FILES['
upfile ']['
tmp_name '],        sprintf('. / uploads / % s. % s ',            sha1_file($_FILES['
upfile ']['
tmp_name ']),            $ext        )    )) {        throw new RuntimeException('
Failed to move uploaded file.
');    }    echo '
File is uploaded successfully.
';} catch (RuntimeException $e) {    echo $e->getMessage();}?>
load more v
22%

Validate and upload single image in PHP , Validate and upload multiple images in PHP ,Single/ multiple image validation and upload in PHP,Validate single/multiple image field using Javascript

Check the html form code below

<form name="myform" action="" method="POST" enctype="multipart/form-data">
   <input type="file" name="f">
   <input type="submit" name="s" value="Submit">
</form>
load more v
60%

Also, if users can then download the uploaded files, there are other steps you should take: redirect to the file and not have a e.g. download.php?file=whatever ; generate a long random filename, if you need to prevent other users from finding it; and more. – AviD ♦ Nov 14 '10 at 10:20 , 2 Another common recommendation is to run all the uploaded files through anti-virus and anti-malware checks (à la virustotal.com). This does not mitigate a skilled attacker from uploading a malicious file which may evade detection, but it does make it more difficult. – Tate Hansen Nov 12 '10 at 21:08 , Stack Exchange network consists of 178 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. , 1 Another important point is to not let the user define name and path of the file, but explicitly define that server side. (I recommend you add this and the AV recommendation from @Tate in your answer...) – AviD ♦ Nov 14 '10 at 10:18

48%

The WYSIWYG editor's PHP SDK comes with the possibility to check the image extension when it is being stored on the disk. Additional to the file name extension, it is using the mime type of the file for better accuracy.,Before storing the image on disk, it is being validated on server side.,You can also pass a custom method instead of validating the extension and mime type. This gives you full control on what types of images you want to store on disk. Below is an example of how to validate if an image is square.,In the Server Upload article we explain the steps to upload an image on your server. When you insert an image in the rich text editor, you can validate its format. However that check is done only on the filename and not on the mime type. We recommend to make additional checks on server side just to make sure that users don't upload images in bad formats.

The WYSIWYG editor's PHP SDK comes with the possibility to check the image extension when it is being stored on the disk. Additional to the file name extension, it is using the mime type of the file for better accuracy.

$options = array(
   'validation' => array(
      'allowedExts' => array('gif', 'jpeg', 'jpg', 'png', 'svg', 'blob'),
      'allowedMimeTypes' => array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/x-png', 'image/png', 'image/svg+xml')
   )
);

// Store the image.
$response = FroalaEditor_Image::upload('/uploads/', $options);
load more v

Other "undefined-undefined" queries related to "Validate that a file is a picture in PHP"