Web Security 24x7

Web Security | Web Hacking | Bug Bounty POC | Web Penetration Testing Tools

Wednesday, November 23, 2016

PHP File Upload With Safe Mode

Uploading Files with PHP

In this tutorial we will learn how to upload files on remote server using a Simple HTML form and PHP. You can upload any kind of file like images, videos, ZIP files, Microsoft Office documents, PDFs, as well as executables files and a wide range of other file types.

In the following example we will store the uploaded file in a upload folder on permanent basis as well as implement some basic security check like file type and file size to ensure that users upload the correct file type and within the allowed limit.
  • <?php
  • if(isset($_FILES["photo"]["error"])){
  •     if($_FILES["photo"]["error"] > 0){
  •         echo "Error: " . $_FILES["photo"]["error"] . "<br>";
  •     } else{
  •         $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
  •         $filename = $_FILES["photo"]["name"];
  •         $filetype = $_FILES["photo"]["type"];
  •         $filesize = $_FILES["photo"]["size"];
  •     
  •         // Verify file extension
  •         $ext = pathinfo($filename, PATHINFO_EXTENSION);
  •         if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
  •     
  •         // Verify file size - 5MB maximum
  •         $maxsize = 5 * 1024 * 1024;
  •         if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
  •     
  •         // Verify MYME type of the file
  •         if(in_array($filetype, $allowed)){
  •             // Check whether file exists before uploading it
  •             if(file_exists("upload/" . $_FILES["photo"]["name"])){
  •                 echo $_FILES["photo"]["name"] . " is already exists.";
  •             } else{
  •                 move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
  •                 echo "Your file was uploaded successfully.";
  •             } 
  •         } else{
  •             echo "Error: There was a problem uploading your file - please try again."; 
  •         }
  •     }
  • } else{
  •     echo "Error: Invalid parameters - please contact your server administrator.";
  • }
  • ?>