How can i download uploaded file from database in php?

In this tutorial you will learn how to force download a file using PHP.

Downloading Files with PHP

Normally, you don't necessarily need to use any server side scripting language like PHP to download images, zip files, pdf documents, exe files, etc. If such kind of file is stored in a public accessible folder, you can just create a hyperlink pointing to that file, and whenever a user click on the link, browser will automatically downloads that file.

<a href="downloads/test.zip">Download Zip file</a>
<a href="downloads/masters.pdf">Download PDF file</a>
<a href="downloads/sample.jpg">Download Image file</a>
<a href="downloads/setup.exe">Download EXE file</a>

Clicking a link that points to a PDF or an Image file will not cause it to download to your hard drive directly. It will only open the file in your browser. Further you can save it to your hard drive. However, zip and exe files are downloaded automatically to the hard drive by default.


Forcing a Download Using PHP

You can force images or other kind of files to download directly to the user's hard drive using the PHP readfile() function. Here we're going to create a simple image gallery that allows users to download the image files from the browser with a single mouse click.

Let's create a file named "image-gallery.php" and place the following code inside it.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Image Gallery</title>
<style type="text/css">
    .img-box{
        display: inline-block;
        text-align: center;
        margin: 0 15px;
    }
</style>
</head>
<body>
    <?php
    // Array containing sample image file names
    $images = array("kites.jpg", "balloons.jpg");
    
    // Loop through array to create image gallery
    foreach($images as $image){
        echo '<div class="img-box">';
            echo '<img src="images/' . $image . '" width="200" alt="' .  pathinfo($image, PATHINFO_FILENAME) .'">';
            echo '<p><a href="download.php?file=' . urlencode($image) . '">Download</a></p>';
        echo '</div>';
    }
    ?>
</body>
</html>

If you see the above example code carefully, you'll find the download link pints to a "download.php" file, the URL also contains image file name as a query string. Also, we've used PHP urlencode() function to encode the image file names so that it can be safely passed as URL parameter, because file names may contain URL unsafe characters.

Here's the complete code of "download.php" file, which force image download.

<?php
if(isset($_REQUEST["file"])){
    // Get parameters
    $file = urldecode($_REQUEST["file"]); // Decode URL-encoded string

    /* Test whether the file name contains illegal characters
    such as "../" using the regular expression */
    if(preg_match('/^[^.][-a-z0-9_.]+[a-z]$/i', $file)){
        $filepath = "images/" . $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);
            die();
        } else {
            http_response_code(404);
	        die();
        }
    } else {
        die("Invalid file name!");
    }
}
?>

Similarly, you can force download other files formats like word doc, pdf files, etc.

The regular expression in the above example (line no-8) will simply not allow those files whose name starts or ends with a dot character (.), for example, it allows the file names such as kites.jpg or Kites.jpg, myscript.min.js but do not allow kites.jpg. or .kites.jpg.

Please check out the tutorial on regular expressions to learn the regular expressions in details.

  • (code link below)

Before we start Read a short article that might interest you.

This will be a short and comprehensive “how-to” on a system built to upload files irrespective of the extension. The file contents will be saved on to a table with some attributes to identify each of the files.

Pre-requisite knowledge required for following along

  1. Basic HTML
  2. PHP
  3. SQL/SQL lite

This will be a fairly simple interface with a PHP command with context stored in the BLOB.

FILES REQUIRED

  1. Upload — this will be used to upload the files into webserver with attributes to identify all the file structures.
  2. Index — this will be used to take input of the attribute with which we are gonna identify the file.
  3. Download — this will the result of a search query.
  4. Download2 — this will be the last page that will actually force out the content.

SQL TABLES

How can i download uploaded file from database in php?

The rows consist of an id thatconsists of integer which auto-increments its value on the addition of more files.

The content is stored in BLOB data type, the rest of the attributes such as names and phone numbers are added in order to recognize which are just added to recognize the file which can be taken as input.

The other rows are the name of the file and extension to see what kind of file is it.

UPLOAD

To upload a file we are gonna create a form and use it to take input of a file and then two text input fields of the name and phone number. Then redirect the action to a function that will validate the inputs and run a query to save it into the table with name as file name and extension.

INDEX

The index file will contain a form that can be called to enter an attribute that will be available to anyone who wants to download.

DOWNLOAD

This file will be the redirect endpoint of the index and will fetch any number of rows which has the attributes in my case phone number which can be download on click.

Download2

This is the file where another query to select the file by its id will be made and finally, the headers will be set to force download the file which has been stored in the content.

The header should be set carefully and the browser permission should for the force download to work.

header("Content-length: $size");header("Content-type: $type");header("Content-Type: application/force-download");header("Content-Disposition: attachment; filename=$name");header("Content-Type: application/octet-stream;");

LINK TO THE CODE

GITHUB CODE

How can I download uploaded file in PHP?

Declare a variable and store the directory name where the downloaded file will save. Use the basename() function to return the file basename if the file path is provided as a parameter. Save the file to the given location. Open the saved file location in write string mode.

How do I download a file from a database?

Follow the same procedure as for Step 4:.
Add the following code: ... .
Browse the files and click on the "Send" button. ... .
Click on the "Download Image from the Database" link then display files, click on the file for downloading..
Display a dialog box, click on "Save"..

How can show uploaded file in PHP?

PHP File Upload.
Configure The "php.ini" File. First, ensure that PHP is configured to allow file uploads. ... .
Check if File Already Exists. Now we can add some restrictions. ... .
Limit File Size. The file input field in our HTML form above is named "fileToUpload". ... .
Limit File Type. ... .
Complete Upload File PHP Script..

How can I download image from database in PHP?

Insert Image File in MySQL. MySQL has a BLOB (binary large object) data type that can hold a large amount of binary data. ... .
Create Database Table. ... .
Database Configuration (dbConfig.php) ... .
Image Upload Form. ... .
Store Image File in Database (upload. ... .
Retrieve image from database (view. ... .
Conclusion..