PHP File Upload and Download

In this tutorial, you will learn how to upload and download files using PHP.

Demo  Source Code

Before start this tutorial, Make sure that PHP is configured to allow file uploads. Any php web server configured with default values set in php.ini file. In your “php.ini” file, search for file_uploads text, and ensure this value is on:

file_uploads = On

Increasing PHP file upload size using php.ini 

upload_max_filesize = 2M

By default, PHP is set to allow uploads of files with a size of 2MB or less. This value limits the size of the maximum allowed size for uploaded files. So change this value whatever your requirements.

post_max_size = 4M

If the upload_max_filesize is larger than post_max_size, you must increase post_max_size so that it is bigger than upload_max_size.

max_execution_time = 30

If you trying to upload files using php it takes some time to upload files, it’s called max_execution_time. When file upload time exceeds max_execution_time limit, the server stops uploading the files. You can modify whatever your requirements.

memory_limit = 32M

When it exceeds this memory the server stops executing the script, then we see the empty page or no response from the server or we get a fatal error.

An Example: We increase file upload size up to 10 MB

upload_max_filesize = 10M
post_max_size = 20M
memory_limit = 128M

Increasing PHP file upload size using .htaccess

php_value upload_max_filesize 10M
php_value post_max_size 20M
php_value memory_limit 128M

Create a .htaccess file on your website root directory and enter the above code into your .htaccess file. That’s it.

 

Now Let’s Start PHP File Upload and Download Tutorial:

PHP File Upload Script

Now we create an HTML form to upload files

<form action="upload.php" method="POST" enctype="multipart/form-data">

	<input type="file" name="data">
	<input type="submit" value="Upload" name="upload">

</form>

Rules for HTML file upload form:

  • The form must be submitted using method=”post”
  • The form also needs to use the following attribute to ensure that the file is correctly uploaded. 
    enctype="multipart/form-data"

  • The type=”file” attribute of the <input> tag shows the input field for upload files.

This HTML form submitted data to a file called upload.php.

Upload.php

Now create a folder called upload. Then create a file called upload.php and Enter the following code to upload files:

<?php
   if(isset($_FILES['data'])){
      $file_name = $_FILES['data']['name'];
      $file_size = $_FILES['data']['size'];
      $file_tmp = $_FILES['data']['tmp_name'];
      $file_type = $_FILES['data']['type'];
      $file_ext=strtolower(end(explode('.',$file_name)));
      $extensions= array("jpeg","jpg","png","txt");
      $target_dir="upload/";

      if(in_array($file_ext,$extensions)){

         if($file_size < 2097152) {

         move_uploaded_file($file_tmp,$target_dir.$file_name);
         echo "File Upload Successfully <br><br>Download Link: 
               <a href='download.php?file=$file_name'>$file_name</a>";
         }
         else{
            echo "Upload Failed! This file size is larger than 2 MB";
         }     
      }
      else{
         echo "Upload Failed! This file type is not allowed";
      }
   }
?>

Upload.php code explained:

  • $file_name specifies uploaded file name.
  • $file_size specifies uploaded file size.
  • $file_tmp specifies a temporary stored uploaded file name.
  • $file_type specifies upload file type.
  • $file_ext is separate file extension from the file name.
  • $extensions are the array of allowed file extension.
  • $target_dir = “uploads/” – specifies the directory where the file is going to be placed.
  • The in_array() function searches an array for a specific value.
  • The move_uploaded_file() function moves an uploaded file to a new location (Upload Folder).

PHP File Download Script

Now we develop a php script for download files. First, create a file called download.php and enter the following code:

<?php
if(isset($_REQUEST["file"])){
    // Decode URL-encoded string
    $file = urldecode($_REQUEST["file"]); 
    
    // File Path
    $filepath = "upload/" . $file;
    
    // Process download
    if(file_exists($filepath)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filepath));
        flush(); // Flush system output buffer
        readfile($filepath);
        exit;
    }
}
?>

Then we request download.php for the file download. If requested file exists on upload directory, Download will start automatically.  An Example:

<a href="download.php?file=file.jpg">Download file</a>

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here