Skip to main content

PHP Image Upload with Size Type Dimension Validation

validate-images
File upload feature requires basic validations to make clean and hygienic the user input. There is a huge chance of exploiting a file upload option with malicious intent. Improper implementation of a file upload input increases security vulnerability. We need to validate the uploaded files before saving them on the server to reduce the vulnerability.


I have created a HTML form and provided an option to upload files. When the form is submitted, the file binaries are sent to the PHP and validated in the server side. I have checked if the uploaded file is an image and I have specified the allowed image extension, size and dimension based on which the validation is taking place. After all these validations have passed, the image file is saved in the target location as specified.
The server-side image file validation takes place in the following aspects.
  • If the file is not empty.
  • If the file extension is one of .jpg, .png, .jpeg.
  • If the file size is less than or 2MB.
  • If the file dimension is within (300X200).

HTML Form with File Input

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 }?>

PHP Code to Validate and Upload Image File

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.
I used PHP function getimagesize() to get the size information to validate the uploaded image in this regard. I specified the allowed image file extensions in an array and validate the uploaded file extension with this array. You can change this array with other preferable image file extension as your wish. After successful validation, the PHP move_uploaded_file() function is used to save the file in the specified target.
<?php
if (isset($_POST["upload"])) {
    // Get Image Dimension
    $fileinfo = @getimagesize($_FILES["file-input"]["tmp_name"]);
    $width = $fileinfo[0];
    $height = $fileinfo[1];
    
    $allowed_image_extension = array(
        "png",
        "jpg",
        "jpeg"
    );
    
    // Get image file extension
    $file_extension = pathinfo($_FILES["file-input"]["name"], PATHINFO_EXTENSION);
    
    // Validate file input to check if is not empty
    if (! file_exists($_FILES["file-input"]["tmp_name"])) {
        $response = array(
            "type" => "error",
            "message" => "Choose image file to upload."
        );
    }    // Validate file input to check if is with valid extension
    else if (! in_array($file_extension, $allowed_image_extension)) {
        $response = array(
            "type" => "error",
            "message" => "Upload valiid images. Only PNG and JPEG are allowed."
        );
        echo $result;
    }    // Validate image file size
    else if (($_FILES["file-input"]["size"] > 2000000)) {
        $response = array(
            "type" => "error",
            "message" => "Image size exceeds 2MB"
        );
    }    // Validate image file dimension
    else if ($width > "300" || $height > "200") {
        $response = array(
            "type" => "error",
            "message" => "Image dimension should be within 300X200"
        );
    } else {
        $target = "image/" . basename($_FILES["file-input"]["name"]);
        if (move_uploaded_file($_FILES["file-input"]["tmp_name"], $target)) {
            $response = array(
                "type" => "success",
                "message" => "Image uploaded successfully."
            );
        } else {
            $response = array(
                "type" => "error",
                "message" => "Problem in uploading image files."
            );
        }
    }
}
?>

PHP Image Upload with Size Type Dimension Validation – Output

The following screenshots showing the success and failure cases while executing PHP image upload with validation example.
image-upload-after-validation
image-validation-error

Comments

Popular posts from this blog

Create facebook messenger chatbot using PHP

Chatbots are the latest sensation in social media communication channels. These automated chat systems are especially build to receive vistiors on social media chats and provide basic information to the visitors about your business. This information could include event schedules, product information, latest deals, store offers and general information about the brand. Entrepreneurs and brand marketers employ chatbots to handle the bulk of chats queries. This way, a large number of queries could be easily handled with minimum costs. Chatbots help reduces the dependence on human customer service representatives (CSR). These chatbots vet out common queries so that the human CSR cold focus on queries that require processing of multiple information sources. Since chatbots steer all conversation toward a pre-set direction, it is easy and time-efficient to use these chatbots instead of human CSR. In this article, I will create a simple Facebook chatbot that could carry out an

Build chatbot with node js and react js

User Experience is given a lot of attention while building any application these days. More and more brands are leveraging chatbots to service their customers, market their brand, and even sell their products. There are a lot of awesome tools out there which helps in building an intelligent bot very easily like Google’s DialogFlow, Amazon Lex, etc, most of which implement their own Natural Language Processing (NLP) logic. However, in some cases, we don’t really need an intelligent bot. Whenever we have a small application having a limited set of options to choose from, it’s not really necessary to use NLP based tools like Google’s DialogFlow. You need to integrate with them (which is pretty easy though), and you need to make a network call to get the results. Instead, you would want to define your rules locally in those cases. Here we will build a simple chatbot using React Simple Chatbot library and add it to our pizza-builder app using which we can build ou

Now About PHP Info

Have you ever heard about phpinfo(). Yes, this function is used to know about configuration details of PHP installed in our machine. Such detailed information returned by this phpinfo() includes platform information, PHP and server environment, HTTP header information, PHP core details like version and directives status, License information and etc. phpinfo() function has an optional argument. If this function is called with no argument, then will display all information. We can check it by executing the following code. <? php phpinfo (); ?> We can also request specific details to be displayed to the browser by passing available constants to this function. Following list shows such available options. INFO_GENERAL – This will return information about the platform, compiler, architecture, API and etc. INFO_CREDITS – This option provides a hyperlink which shows details about authors, documentation, QA and infrastructure team. INFO_CONFIGURATION – Disp