Form Handling & Secure Uploading

Form Handing in PHP is easy

Example : HTML POST Form

<form action="filename.php" method="POST">
Your name: <input type=text name=name><br>
You age: <input type=text name=age><br>
<input type=submit>
</form>

Receiving data on our "index.php" file To receive any input where "method='post'" in HTML form, $_POST is used.

Hi .  <?php echo htmlspeciachars($_POST['name']); ?>.
You are <?php echo (int)$_POST['age']; ?>. years old.

Example 2: HTML GET Form

<form action="filename.php" method="GET">
Your name: <input type=text name=name><br>
You age: <input type=text name=age><br>
<input type=submit>
</form>

Receiving data on our "index.php" file To receive any input where "method='get'" in HTML form, $_GET is used

Hi .  <?php echo htmlspeciachars($_GET['name']); ?>.
You are <?php echo (int)$_GET['age']; ?>. years old.

Difference "GET" and "POST"

In "method='get'" , All data passed or submitted in form are visible on URL like : http://example.com/index.php?name=John&age=30 , whereas 

In "method='post'" , All data passed or submitted in form are not visible via URL , i.e, URL will still be :-http://example.com/index.php

Form Uploading 

Form uploading is critical and requires huge attention , as single mistake can leave your site for vulnerability , So watch them properly.

1. Let's consider first image.  How to Securely Upload Image in php ?

HTML Form Below  :-

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Image Uploading</title>
</head>
<body>
    <form action="uploadImage.php" method="post" enctype="multipart/form-data">
        <label for="image">Upload Image</label>
        <!-- You can either specify any particular extension type as below like ",jpg,.png" etc -->
        <input id="uploadImage" type="file" name="uploadImage" accept=".jpg">

        <!-- 

Or, you can simply call the "image/*" which will accept all types of image including gif,bmp etc

   <input type="file" name="uploadImage" accept="image/*">


Syntax is :-

| below means or 

<input accept="file_extension|audio/*|video/*|image/*|media_type">
-->

    </form>
</body>
</html>

PHP Secure Image Upload PHP Script Below :- 

 <?php

    $myfileInfo = finfo_open(FILEINFO_MIME_TYPE); // returns mime type.

// file input name is uploadImage this we wil be using $_FILES global variable
// More read here :- http://php.w3clan.com/tutorial/71/get-post-cookie-request-server-files-session  Search $_FILES


   // We are checking file mime type.

    $mime = finfo_file($myfileInfo, $_FILES['uploadImage']['tmp_name']);

    // Valid Image type array

    $validImageArray = array('image/gif', 'image/jpeg', 'image/png');

    if (in_array($mime, $validImageArray)) {

        // Image is valid, now we can go with compress image.

        $target_dir = "uploads/";

        $target_file = $target_dir . basename($_FILES["uploadImage"]["name"]);

        if (move_uploaded_file($_FILES["uploadImage"]["tmp_name"], $target_file)) {

            echo "The file ". basename( $_FILES["uploadImage"]["name"]). " has been uploaded.";

        } else {

            echo "Sorry, there was an error uploading your file.";

        }
    }

finfo_close($myfileInfo);

?>
2. Other Upload Type :-

If you want to allow users to upload other file type , you can simply change below code in above code with your allowed file type :-

$validImageArray = array('image/gif', 'image/jpeg', 'image/png');

// Change above value inside array to your required file type mime.
Short List of Mime Type:- 
<?php

 $mime_types = array(

            'txt' => 'text/plain',
            'htm' => 'text/html',
            'html' => 'text/html',
            'php' => 'text/html',
            'css' => 'text/css',
            'js' => 'application/javascript',
            'json' => 'application/json',
            'xml' => 'application/xml',
            'swf' => 'application/x-shockwave-flash',
            'flv' => 'video/x-flv',

            // images
            'png' => 'image/png',
            'jpe' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'jpg' => 'image/jpeg',
            'gif' => 'image/gif',
            'bmp' => 'image/bmp',
            'ico' => 'image/vnd.microsoft.icon',
            'tiff' => 'image/tiff',
            'tif' => 'image/tiff',
            'svg' => 'image/svg+xml',
            'svgz' => 'image/svg+xml',

            // archives
            'zip' => 'application/zip',
            'rar' => 'application/x-rar-compressed',
            'exe' => 'application/x-msdownload',
            'msi' => 'application/x-msdownload',
            'cab' => 'application/vnd.ms-cab-compressed',

            // audio/video
            'mp3' => 'audio/mpeg',
            'qt' => 'video/quicktime',
            'mov' => 'video/quicktime',

            // adobe
            'pdf' => 'application/pdf',
            'psd' => 'image/vnd.adobe.photoshop',
            'ai' => 'application/postscript',
            'eps' => 'application/postscript',
            'ps' => 'application/postscript',

            // ms office
            'doc' => 'application/msword',
            'rtf' => 'application/rtf',
            'xls' => 'application/vnd.ms-excel',
            'ppt' => 'application/vnd.ms-powerpoint',

            // open office
            'odt' => 'application/vnd.oasis.opendocument.text',
            'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
        );


?>

Full list of Mime type :- http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

Important Note : Uploading are very critical thing, as it can allow hackers to upload malicious files and infect server or users using your app or web. So be careful while alllowing Variety of Mime types.    

For Secure Image Uploading. Code we have specified above is secure and you can definitely use in your production site.

But Please be aware of vulnerability or bug if any arises in future. w3clan would not be responsible for any vulnerability or bug occurs on any PHP function used above.

Also Importantly Disable php engine in your upload directory by adding/creating .htaccess file in your upload directory.

// Create file with name ".htaccess" inside directory where user uploads image and copy paste below value.

php_flag engine off

Loading ...

About the Author