Question Detail

Creating an upload script

There is one global PHP variable called $_FILES. This variable is an associate double dimension array and keeps all the information related to uploaded file. So if the value assigned to the input's name attribute in uploading form was file, then PHP would create following five variables −

  • $_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.

 

Example:

Below example should allow upload images and gives back result as uploaded file information.

<?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'])));
      
      $expensions= array("jpeg","jpg","png");
      
      if(in_array($file_ext,$expensions)=== 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>


Thread Reply

Hemant Sharma

- 1 years ago

Posting this snipped that I wrote so that if someone else comes here wanting to upload multiple files would not return empty-handed. :) This script does not perform any validation. It just does straight upload. Feel free to customize this basic code as you need.

HTML FORM

<form action="upload_Class.php" method="POST" enctype="multipart/form-data">
   Select images: <input type="file" name="files[]" multiple>
   <input type="submit">
</form>

upload_Class.php

$move = "\uploads";
foreach ($_FILES["files"]["tmp_name"] as $key => $value) 
{
     $tmp_name = $_FILES["files"]["tmp_name"][$key];
     $name = $move ."\\".basename($_FILES["files"]["name"][$key]);
     move_uploaded_file($tmp_name, $name);
}