PHP File Upload

PHP allows you to upload single and multiple files on remote server using a Simple HTML form. You can upload any kind of file like images, videos, ZIP files, PDFs, as well as executables files.

$_FILES['file'] contains the information about the uploaded file. Each of these per-file arrays has five elements:

  • $_FILES['file']['name']: The name of the uploaded file. This is supplied by the browser so it could be a full pathname or just a filename.
  • $_FILES['file']['type']: The MIME type of the file, as supplied by the browser.
  • $_FILES['file']['size']: The size of the file in bytes, as calculated by the server.
  • $_FILES['file']['tmp_name']: The location in which the file is temporarily stored on the server.
  • $_FILES['file']['error']: An error code returns what (if anything) went wrong with the file upload.

PHP File Upload Example

file: upload_form.html


<form action="upload.php" method="post" enctype="multipart/form-data">
 <div class="form-group">
   <label for="file">File:</label>
   <input type="file" name="file" class="form-control" id="file" />
</div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>

file: upload.php

<?php
  $upload_dir = "/upload_dir/";
  $upload_dir = $upload_dir . basename($_FILES['file']['name']);
  if (move_uploaded_file(basename($_FILES['file']['tmp_name'], $upload_dir)) { 
      echo "Uploaded Successfully!";
  } else { 
      echo "File not uploaded, Please try again!";
  }
?>