Single/ multiple image validation and upload in PHP

by  
Share:
Validate single/ multiple image

In my last snippet I have explained how to validate single/multiple image field using JavaScript, but the rule of thumb is “NEVER TRUST USER”. User can try to upload malicious file using different techniques and javaScript validation is not secure. So what we do, we validate the image both at client and server side. In this tutorial I am going to explain how to validate Single/multiple image field and and upload in PHP.

Validate and upload single image in PHP

I am going to create a file called index.php where I am going to code and test my image validation code. First of all I am going to create a form with a file field and a submit button and upon form submission I am going to validate the file if its an image or not and upon validation I will upload it to the server. Also create a folder called “uploads” (you can give whatever name you want) on your server and make sure you have write permission to that folder.

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>

Once the html form is created just write the php code above the form code ( strongly recommended). I am validating image of type jpg, gif,png and bmp.
<?php
if (isset($_POST["s"])) {

    // image mime to be checked against
    $imagetype = array(image_type_to_mime_type(IMAGETYPE_GIF), image_type_to_mime_type(IMAGETYPE_JPEG),
        image_type_to_mime_type(IMAGETYPE_PNG), image_type_to_mime_type(IMAGETYPE_BMP));

    $error_msg = "";
    $imageUploadERROR = FALSE;
    $FOLDER = "uploads/";
    if ($_FILES["f"]["name"] <> "" && $_FILES["f"]["error"] == 0) {
        // uploaded file is OK
        
        if (in_array($_FILES["f"]["type"], $imagetype)) {
            // get the extention of the file
            $file_extention = @strtolower(@end(@explode(".", $_FILES["f"]["name"])));
            // Setting an unique name for the file
            $file_name = date("Ymd") . '_' . rand(10000, 990000) . '.' . $file_extention;

            if (move_uploaded_file($_FILES["f"]["tmp_name"], $FOLDER . $file_name) === FALSE) {
                $error_msg = "Error while uploading the file";
            } else {
                $error_msg = "File uploaded successfully with name: " . $file_name;
            }
        } else {
            $error_msg = "File is not a valid image type.";
        }

        if ($imageUploadERROR === FALSE) {
            // Failed to upload file, you can write your code here
            echo $error_msg;
        } else {
            // file is uploaded, you can write your code here
            echo $error_msg;
        }
    }
}
?>

Once you are done with this tutorial have a look at these posts as well, it will definitely help you.

Validate and upload multiple images in PHP

Once you know how validation and upload code for single image works, uploading multiple image will just be a piece of cake. The primary difference when validating between single and multiple image fields is that the single image is a array whereas the multiple image field is an array of arrays. Have a look at their internal structure when I upload single image vs multiple images.

// sample single image file during upload
Array
(
    [name] => casio1.jpg
    [type] => image/jpeg
    [tmp_name] => D:\xampp\tmp\phpC3BD.tmp
    [error] => 0
    [size] => 42020
)

// sample multiple image file during upload ( for two images)
Array
(
    [name] => Array
        (
            [0] => casio1.jpg
            [1] => casio2.jpg
        )

    [type] => Array
        (
            [0] => image/jpeg
            [1] => image/jpeg
        )

    [tmp_name] => Array
        (
            [0] => D:\xampp\tmp\phpE542.tmp
            [1] => D:\xampp\tmp\phpE543.tmp
        )

    [error] => Array
        (
            [0] => 0
            [1] => 0
        )

    [size] => Array
        (
            [0] => 42020
            [1] => 295800
        )

)


As you have seen, during multiple file upload you get an array of array of file field. Now let me code how to validate and upload multiple file field. Let me first start with creating a form that will accept multiple files. Please note that the name of the file field is “f[]” which represent an array.
<form name="myform" action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="f[]" multiple="" >
    <input type="submit" name="s" value="Submit">
</form>

Once the user attach multiple file and submit the form, it will validate and upload the image file on the server. Have a look at the PHP code below.
<?php
if (isset($_POST["s"])) {

    // image mime to be checked against
    $imagetype = array(image_type_to_mime_type(IMAGETYPE_GIF), image_type_to_mime_type(IMAGETYPE_JPEG),
        image_type_to_mime_type(IMAGETYPE_PNG), image_type_to_mime_type(IMAGETYPE_BMP));

    $error_msg = "";
    $imageUploadERROR = FALSE;
    $FOLDER = "uploads/";
    $myfile = $_FILES["f"];

    for ($i = 0; $i < count($myfile["name"]); $i++) {

        if ($myfile["name"][$i] <> "" && $myfile["error"][$i] == 0) {
            // uploaded file is OK

            if (in_array($myfile["type"][$i], $imagetype)) {
                // get the extention of the file
                $file_extention = @strtolower(@end(@explode(".", $myfile["name"][$i])));
                // Setting an unique name for the file
                $file_name = date("Ymd") . '_' . rand(10000, 990000) . '.' . $file_extention;

                if (move_uploaded_file($myfile["tmp_name"][$i], $FOLDER . $file_name) === FALSE) {
                    $error_msg = "Error while uploading the file";
                } else {
                    $error_msg = "File uploaded successfully with name: " . $file_name;
                }
            } else {
                $error_msg = "File is not a valid image type.";
            }
        }

        if ($imageUploadERROR) {
            // if upload error break the loop and display the error
            break;
        }
    }

    if ($imageUploadERROR === FALSE) {
        // Failed to upload file, you can write your code here
        echo $error_msg;
    } else {
        // file is uploaded, you can write your code here
        echo "All file is uploaded successfully";
    }
}
?>

You can similarly validate other files extension like PDF, excel, word and many more, I have already posted a list of common mime type here.

If you guys have some suggestion/feedback please share with us.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

tharani on

please help me beginning the stage in php developing send me a sample validation code for signup page and i need image validation code

Reply
Shahrukh Khan on

both are available, check my php category.

Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.