PHP script can be used in HTML form to allow users to upload files to a server. Initially the files are uploaded to a temporary directory and then moved to the location specified by the PHP text.

The information on the phpinfo.php page describes the temporary directory used for uploading files such as upload_tmp_dir and the maximum permissible size of files that can be uploaded as upload_max_filesize. These frameworks are set in the PHP configuration file php.ini


Creating an upload form

The following HTM code below creates an uploader form. This form is having method attribute set to post and enctype attribute is set to multipart/form-data

#upload.php

<html>
   <body> 
      <form action="" method="POST" enctype="multipart/form-data">
         <input type="file" name="image" />
         <input type="submit"/>
      </form>
   </body>
</html>


Creating an upload script

There is one global PHP varible called $ _FILES. This fluctuates in double-dimension array and saves all information related to the uploaded file. So if the value assigned to the input's name attribute on the upload form was a file, PHP will create the following five variables -


#complete_file_upload.php

<?php
   if(isset($_FILES['image'])){
      $errors= array();
      $file_name = $_FILES['image']['name'];
      $file_size = $_FILES['image']['size'];
      $file_tmp = $_FILES['image']['tmp_name'];
      $file_type = $_FILES['image']['type'];
      $file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
      
      $extensions= array("jpeg","jpg","png");
      
      if(in_array($file_ext,$extensions)=== false){
         $errors[]="extension not allowed, please choose a JPEG or PNG file.";
      }
      
      if($file_size > 2097152) {
         $errors[]='File size must be excately 2 MB';
      }
      
      if(empty($errors)==true) {
         move_uploaded_file($file_tmp,"images/".$file_name);
         echo "Success";
      }else{
         print_r($errors);
      }
   }
?>
<html>
   <body>
      
      <form action = "" method = "POST" enctype = "multipart/form-data">
         <input type = "file" name = "image" />
         <input type = "submit"/>
   
         <ul>
            <li>Sent file: <?php echo $_FILES['image']['name'];  ?>
            <li>File size: <?php echo $_FILES['image']['size'];  ?>
            <li>File type: <?php echo $_FILES['image']['type'] ?>
         </ul>
   
      </form>
      
   </body>
</html>


  • $_FILES['file']['tmp_name'] − the uploaded file in the temporary directory on the web server.
  • $_FILES['file']['name'] − the actual name of the uploaded file.
  • $_FILES['file']['size'] − the size in bytes of the uploaded file.
  • $_FILES['file']['type'] − the MIME type of the uploaded file.
  • $_FILES['file']['error'] − the error code associated with this file upload.