How to Download File Using PDO in PHP

By CampCodes Administrator

Updated on:

download a file using pdo

In this tutorial, we will create a Simple Download File using PDO. This code can download an uploaded file from the database server with a PDO query. The system uses a PDO SELECT query to fetch the data that will be downloaded, then use PHP header() by adding some parameters and to download the file, you must declare the filename of the file inside the function.

We will be using PDO as a query scripting it an acronym for PHP Data Objects. It is a lean, clean, and consistent way to access databases. This means developers can write portable code much more accessible.

Getting Started:

First, you have to download & install XAMPP or any local server that runs PHP scripts. Here’s the link for the XAMPP server https://www.apachefriends.org/index.html.

And, this is the link for the bootstrap that I used for the layout design https://getbootstrap.com/.

Creating Database

Open your database web server then create a database name in it db_pdo_download, after that, click Import then locates the database file inside the folder of the application then click ok.

download a file using pdo

Creating the database connection

Open your any kind of text editor(notepad++, etc..). Then just copy/paste the code below then name it conn.php.

<?php
    $conn = new PDO( 'mysql:host=localhost;dbname=db_pdo_download', 'root', '');
    if(!$conn){
        die("Fatal Error: Connection Failed!");
    }
?>

Creating The Interface

This is where we will create a simple form for our application. To create the forms simply copy and write it into your text editor, then save it as index.php.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
    </head>
<body>
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
        </div>
    </nav>
    <div class="col-md-3"></div>	
    <div class="col-md-6 well">
        <h3 class="text-primary">PHP - Simple Download File Using PDO</h3>
        <hr style="border-top:1px dotted #ccc;"/>
        <center>
            <form method="POST" action="upload.php" enctype="multipart/form-data">
                <div class="form-inline">
                    <input type="file" class="form-control" name="file" required="required"/>
                    <button class="btn btn-primary" name="upload"><span class="glyphicon glyphicon-upload"></span> Upload</button>
                </div>
            </form>
        </center>
        <br />
        <table class="table table-bordered">
            <thead class="alert-info">
                <tr>
                    <th>File</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php
                    require 'conn.php';
                    $query = $conn->prepare("SELECT * FROM `file`");
                    $query->execute();
                    while($fetch = $query->fetch()){
                ?>
                <tr>
                    <td><?php echo $fetch['file']?></td>
                    <td><a href="download.php?file_id=<?php echo $fetch['file_id']?>" class="btn btn-primary">Download</a></td>
                </tr>
                <?php
                    }
                ?>
            </tbody>
        </table>
    </div>
</body>	
</html>

Creating the Upload Function

This code contains the upload function of the application. This code will store the data file to the database server when the button is clicked. To do this just kindly write these block of codes inside the text editor, then save it as upload.php.

<?php
    require_once 'conn.php';
 
    if(ISSET($_POST['upload'])){
        $file_name = $_FILES['file']['name'];
        $file_temp = $_FILES['file']['tmp_name'];
        $file_size = $_FILES['file']['size'];
        $exp = explode(".", $file_name);
        $ext = end($exp);
        $name = date("Y-m-d h-i-s").".".$ext;
        $path = "uploads/".$name;
 
        if($file_size > 5242880){
            echo "<script>alert('File too large')</script>";
            echo "<script>window.location='index.php'</script>";
        }else{
            try{				
                if(move_uploaded_file($file_temp, $path)){
                    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    $sql = "INSERT INTO `file` (`file`, `location`) VALUES ('$name', '$path')";
                    $conn->exec($sql);
                }
 
            }catch(PDOException $e){
                echo $e->getMessage();
            }
 
            $conn = null;
 
            header('location:index.php');
        }
    }
?>

Creating the Main Function

This code contains the main function of the application. This code will download the file when the button is clicked. To do this just kindly write these block of codes inside the text editor, then save it as download.php.

<?php
    require_once 'conn.php';
 
    if(ISSET($_REQUEST['file_id'])){
        $file = $_REQUEST['file_id'];
        $query = $conn->prepare("SELECT * FROM `file` WHERE `file_id`='$file'");
        $query->execute();
        $fetch = $query->fetch();
 
        header("Content-Disposition: attachment; filename=".$fetch['file']);
        header("Content-Type: application/octet-stream;");
        readfile("uploads/".$fetch['file']);
    }
?>

There you have it we successfully created a Simple Download File using PDO. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

 

Next Step for Your Project Journey

Pick your next action to keep building: download complete source code, continue with practical tutorials, or explore more project systems.

Explore Source Code Continue Tutorials Final Year Projects
application docx php code for downloading a file in php code for file upload in php with mysql data type for file upload in mysql download a file using pdo download file in php download file php download file using php pdo download image in php download pdf file from database in php download pdf file in php download pdf file in php code download pdf file in php script download pdf in php download php file file download code in php file download code in php with demo file download counter html code file download in php file downloading in php file upload and download in php example code file upload and download in php source code file upload in php file upload in php example code demo file upload in php mysql database file upload in php mysql example file upload php example download file validation in php force download image php how to download file in php how to download file using php code how to insert audio file in mysql database using php how to insert pdf file in mysql database how to make a file downloadable in php how to retrieve uploaded file in php how to store doc file in mysql database how to store doc file in mysql database using php how to store file path in mysql using php how to store files in mysql database how to store files in mysql database using php how to store mp3 file in mysql database using php how to store pdf file in database using php how to store pdf file in mysql database how to store pdf file in mysql database using php how to store word documents in mysql database using php how to upload audio file in database using php how to upload pdf file in mysql database using php how to upload resume in php mysql html code form with upload file and send html file upload example javascript move uploaded file in php move uploaded file in php w3schools mysql upload file new pdo php on click download file php pdf file upload and download in php pdf file upload in php example pdo file pdo mcps pdo php php 7 file upload php auto download file on page load php code for downloading a file from database php code for downloading a file from folder php code for downloading a file from server php code for downloading file from mysql database php code to download a file php code to download a file from server php code to download multiple files php download a file php download all files in directory php download file php download file from server php download file from server to client php download file from server to local php download file from url php download file from url to client php download file from url to computer php download file script php download file to client php download file to server php download image file php download image from folder php download image from server php download large file from url php download manager script php download pdf php download pdf file php download script php download zip file from server php file download php file download example php file download script php file download script example php file downloader php file upload php file upload and download management system php file upload and download script php file upload and download script free php file upload and download tutorial php file upload download script php file upload script php file upload script github php force download php force download file php force download file from url php force download image php force download pdf php force download text file php header download file php image download script php javascript file upload php mysql file upload and download script php mysql file upload example php mysql file upload script php output file php pdo php pdo example php pdo update php pdo upload file script php script download php script for downloading files php script to download file from url php secure file download php secure file upload php send file to browser php serve file php stream file php tutorial php tutorials php upload file to another server php upload file type php uploader php zip directory and download php zip folder and download post php file download script file download secure php file upload script simple php file upload script download source code upload file php store file in database php tutorialspoint file upload in php upload files in php code example upload files to database upload image in php mysql database and display demo upload image in php mysql database example upload image in php mysql database w3schools upload only a .pdf .doc .docx or .txt file in php upload only pdf file in php upload pdf file in php uploading and downloading files in php and mysql uploading and downloading files in php and mysqli video upload code in php free download viewing pdf files stored in mysql database using php what is pdo php extension?

Leave a Comment