how to validate format and size of uploaded file via php

Solutions on MaxInterview for how to validate format and size of uploaded file via php by the best coders in the world

showing results for - "how to validate format and size of uploaded file via php"
Jessica
17 Oct 2016
1<?php
2if (isset($_POST["upload"])) {
3    // Get Image Dimension
4    $fileinfo = @getimagesize($_FILES["file-input"]["tmp_name"]);
5    $width = $fileinfo[0];
6    $height = $fileinfo[1];
7    
8    $allowed_image_extension = array(
9        "png",
10        "jpg",
11        "jpeg"
12    );
13    
14    // Get image file extension
15    $file_extension = pathinfo($_FILES["file-input"]["name"], PATHINFO_EXTENSION);
16    
17    // Validate file input to check if is not empty
18    if (! file_exists($_FILES["file-input"]["tmp_name"])) {
19        $response = array(
20            "type" => "error",
21            "message" => "Choose image file to upload."
22        );
23    }    // Validate file input to check if is with valid extension
24    else if (! in_array($file_extension, $allowed_image_extension)) {
25        $response = array(
26            "type" => "error",
27            "message" => "Upload valiid images. Only PNG and JPEG are allowed."
28        );
29        echo $result;
30    }    // Validate image file size
31    else if (($_FILES["file-input"]["size"] > 2000000)) {
32        $response = array(
33            "type" => "error",
34            "message" => "Image size exceeds 2MB"
35        );
36    }    // Validate image file dimension
37    else if ($width > "300" || $height > "200") {
38        $response = array(
39            "type" => "error",
40            "message" => "Image dimension should be within 300X200"
41        );
42    } else {
43        $target = "image/" . basename($_FILES["file-input"]["name"]);
44        if (move_uploaded_file($_FILES["file-input"]["tmp_name"], $target)) {
45            $response = array(
46                "type" => "success",
47                "message" => "Image uploaded successfully."
48            );
49        } else {
50            $response = array(
51                "type" => "error",
52                "message" => "Problem in uploading image files."
53            );
54        }
55    }
56}
57?>
58