PHP File Upload


Using PHP to Upload Files

In this tutorial, we'll learn how to use a Simple HTML form and PHP to upload files to a remote server. You can upload any file form, including photos, videos, ZIP files, Microsoft Office documents, PDFs, executables, and a variety of other file types.


Create an HTML form to upload the file as the first step.

The example below shows how to make a basic HTML form that can be used to upload files.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload Form</title>
</head>
<body>
<form action="upload-manager.php" method="post" enctype="multipart/form-data">
<h2>Upload File</h2>
<label for="fileSelect">Filename:</label>
<input type="file" name="photo" id="fileSelect">
<input type="submit" name="submit" value="Upload">
<p><strong>Note:</strong> Only .jpg, .jpeg, .gif, .png formats allowed to a max size of 5 MB.</p>
</form>
</body>
</html>



Step 2: Examining the file that has been uploaded

The complete code for our "upload-manager.php" file can be found below. It will save the uploaded file in a permanent "upload" folder and perform some basic security checks, such as file type and file size, to ensure that users upload the correct file type and stay within the permitted file size limits.


<?php
  // Check if the form was submitted
  if($_SERVER["REQUEST_METHOD"] == "POST"){
   // Check if file was uploaded without errors
  if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
  $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: Kindly select a valid file format.");

  // Verify file
  // size - 5MB maximum
  $maxsize = 5 * 1024 * 1024;
  if($filesize > $maxsize) die("Error: The File size is larger. This is above 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/" . $filename)){
    echo $filename . " is already exists.";
  }
  else{
    move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $filename);
    echo "Your Uploaded successfully.";
  }
  }
  else{
    echo "Error: There was a problem while we try uploading your file. Kindly try again.";
  }
  }
  else{
    echo "Error: " . $_FILES["photo"]["error"];
  }
  }
?>