How to Download File Using PDO in PHP

June 23, 2020
PHP
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!

 

Facebook Comments
https://www.campcodes.com/

This is a free education portal. You can use every source code in your project without asking permission to the author. Share our website to everyone to make our community of programmers grow more.

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a Reply

Your email address will not be published.