PHP 

A force-download script can give you more control over a file download than you would have providing a direct link that may be the good thing most of the time to read it online. But sometimes it can be very frustrating to click on a link to a document you want people to read, and then have to wait for it to download and finally open on your computer that may not have the right program to open it.

But what if you have a file you want people to download ? If it is an HTML file or a PDF file or an image file or a video file, you cannot just post link, as the web browsers open those automatically; instead you need to do some tricky thing using PHP.

PHP allows you to change the HTTP headers of files that you are writing, so that you can force a file to be downloaded that normally the browser would load in the same window. This is perfect for files like PDFs, document files, images, and video that you want your customers to download rather than read online.
If you have any query please feel free to send a query.

Prerequisites

PHP 5.4
MySQL 5.5
Apace http Server 2.4
Netbeans 7.4 (Optional)

Step 1. Creates a php projects using Netbeans or create a project directory under htdocs.

Step 2. Create a php file called config.php with the below source code in the project directory

<?php

ini_set('display_errors', 'On');

error_reporting(E_ALL);

// setting up the web root and server root
$thisFile = str_replace('\\', '/', __FILE__);
$docRoot = $_SERVER['DOCUMENT_ROOT'];

$webRoot = str_replace(array($docRoot, 'config.php'), '', $thisFile);
$srvRoot = str_replace('config.php', '', $thisFile);

define('SRV_ROOT', $srvRoot);

require_once 'common.php';

/*
* End of file config.php
*/

Step 3. Create a common.php file with below source code in the project directory. Please go through tutorial https://www.roytuts.com/get-mime-type-from-file-extension-using-php/ for $mimes array

//force file download
function force_download($filename = '', $path = '') {

    if ($filename == '' OR $path == '') {
        return FALSE;
    }

    // Try to determine if the filename includes a file extension.
    // We need it in order to set the MIME type
    if (FALSE === strpos($filename, '.')) {
        return FALSE;
    }

    $data = file_get_contents($path . $filename);

    // Grab the file extension
    $x = explode('.', $filename);
    $extension = end($x);

    // Set a default mime if we can't find it
    if (!isset($mimes[$extension])) {
        $mime = 'application/octet-stream';
    } else {
        $mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension];
    }

    // Generate the server headers
    if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") !== FALSE) {
        header('Content-Type: "' . $mime . '"');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header("Content-Transfer-Encoding: binary");
        header('Pragma: public');
        header("Content-Length: " . strlen($data));
    } else {
        header('Content-Type: "' . $mime . '"');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header("Content-Transfer-Encoding: binary");
        header('Expires: 0');
        header('Pragma: no-cache');
        header("Content-Length: " . strlen($data));
    }

    exit($data);
    
}

Step 4. Create a php web page download.php with the following source code

<?php
require_once 'config.php';

if (isset($_POST['download'])) {
    force_download('pclzip.lib.php', SRV_ROOT);
}
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <form method="post"    action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
            <h3>Force Download</h3>
            <div>
                <input type="submit" name="download" value="Download"/>
            </div>
        </form>
    </body>
</html>

Step 5. Run the php file download.php. You will get the file opened in new window for “Open with” or “Save” options.

That’s all. Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials | TwitterFacebook Google PlusLinkedin | Reddit | Email Me

Leave a Reply

Your email address will not be published. Required fields are marked *