PHP File Upload

In PHP we can also upload single or multiple files on the web server.  The files are uploaded into a temporary directory on the server and after the completion of uploading, the file is relocated to a target destination by a php script. Also note that to enable the file uploads on your php server setup, you have to set the file_uploads directive to On. In XAMPP Setup its sets in On by default.
 file_uploads = On
Now lets see a simple example of file upload page in PHP.
<html>
<body>

  <form action="" method="post" enctype="multipart/form-data">
    Select File :
    <input type="file" name="imgFile"><br/><br/>
    <input type="submit" value="Upload File" name="submit">
  </form>
<br/>

<?php

  if($_SERVER["REQUEST_METHOD"] == "POST") {
    $fileStorage = "uploads/";
    $fileStorage .= $_FILES['imgFile']['name'];

    if(move_uploaded_file($_FILES["imgFile"]["tmp_name"], $fileStorage)) {
      echo "File : <b>" . $_FILES['imgFile']['name'] . "</b> is Successfully uploaded.";
    } else {
      echo "Sorry, File was not uploaded. Some Error Occured.";
    }
  }

?>

</body>
</html>
Output :



Explanation of Above Code :

HTML Form :
<form action="" method="post" enctype="multipart/form-data">
  Select File :
  <input type="file" name="imgFile"><br/><br/>
  <input type="submit" value="Upload File" name="submit">
</form>
In the HTML form, it is necessary to use the POST method when we upload a file or files, and we also need to use the enctype attribute, which is :
 enctype="multipart/form-data"
It specifies which content-type to use when submitting the form. And for the File-Select control the file input field is used, which is defined by :
 <input type="file" name="imgFile">
The above statement define the File-Select control, with a "Browse" button.


PHP Code :
<?php

  if($_SERVER["REQUEST_METHOD"] == "POST") {
    $fileStorage = "uploads/";
    $fileStorage .= $_FILES['imgFile']['name'];

    if(move_uploaded_file($_FILES["imgFile"]["tmp_name"], $fileStorage)) {
      echo "File : <b>" . $_FILES['imgFile']['name'] . "</b> is Successfully uploaded.";
    } else {
      echo "Sorry, File was not uploaded. Some Error Occured.";
    }
  }

?>
At the above php code, if condition is used to check that the method is post then the code will executed. And the variable $fileStorage stores the path and name of the image file on the server, where we want to store the image on the server (On line 4 and 5).

When we upload a file on php, then it will initially stored on a temporary directory and then relocated to a target destination  by using move_upload_file() function, which moves the uploaded file to its destined location. The move_uploaded_file() function checks internally if the file is uploaded thorough the POST request. It moves the file if it is uploaded through the POST request. The syntax of move_upload_file() is :
 move_upload_file( fileName, Destination);
where fileName is name of the uploaded file in temporary directory ( $_FILES["imgFile"]["tmp_name"] ), and Destination is the destination of file where you want to store that file. In line 6th the move_upload_file() function is used.

PHP $_FILES Gloabal Variable :

The php global variable $_FILES is a two dimensional array, which contains all the information related to the uploaded file. The information of uploaded file can be accessed by the file input filed's name attribute, which is at the above example is 'imgFile'. With $_FILES variable we can get file name, file type, file size, temp file name and errors associated with file.

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

Now lets an example with more control over file uploads  :

Example 1 :

The Following PHP code will only accepts certain type of files within the given size limits, and shows the information about the uploaded file.
<html>
<body>

<form action="" method="post" enctype="multipart/form-data">
  Select File :
  <input type="file" name="imgFile"><br/><br/>
  <input type="submit" value="Upload File" name="submit">
</form>

<br/>

<?php

  if($_SERVER["REQUEST_METHOD"] == "POST") {
    if(isset($_FILES["imgFile"]) && $_FILES["imgFile"]["error"] == 0) {
      $err = array();

      $fileName = $_FILES['imgFile']['name'];
      $fileSize = $_FILES['imgFile']['size'];
      $file_type = $_FILES['imgFile']['type'];
      $fileStorage = "uploads/";
      $targetFile = $fileStorage . $fileName;

      // getting the file extension
      $fileExtension = strtolower(end(explode('.', $_FILES['imgFile']['name'])));

      $allowedExtensions = array("jpg", "jpeg", "gif", "png");

      // checking the file extension
      if(in_array($fileExtension, $allowedExtensions) === false) {
        $err[] = "Uploaded File Extension not allowed, please upload files with JPG, JPEG, GIF and PNG file extension.";
      }

      // checking file size (less than 2 MB)
    
      $maxSize = 1024 * 1024 * 2; 
      if($fileSize > $maxSize) {
        $err[] = 'File size must be under 2 MB.';
      }

      // check if file already exists
      if(file_exists($targetFile)) {
        $err[] = "The File : $fileName already exists.";
      }

      if(empty($err) == true) {
        if(move_uploaded_file($_FILES["imgFile"]["tmp_name"], $targetFile)) {
          echo "File : <b>" . $_FILES['imgFile']['name'] . "</b> is Successfully uploaded.";
        } else {
          echo "Sorry, File was not uploaded. Some Error Occured.";
        }
      } else {
        print_r($err);
      }
    } else {
      echo "Error: " . $_FILES["imgFile"]["error"];
    }
  }

?>

</body>
</html>
Output :



Next Topic :