user3212453
user3212453

Reputation: 11

Download pdf and image files with php instead of displaying them on your desktop

I have created a script that works only with some files and I would like to improve it. In practice, this PHP script saves the uploaded file on the server disk and the file name in a mySQL database.

When I press on the download button, the script saves the name of the file into $filenameso when I use the code shown below, I'm able to download the file:

header ("Location: http://". $ _SERVER ['SERVER_NAME']. "/ FILE_DOWNLOAD /". $ filename);

The problem is that if the file is an image or a PDF and I try to open it from my browser, it opens the file instead of downloading it to my desktop.

I've looked for a solution on many forums but have had no success.

Here's an alternative that is very close to what I'm looking for:

$files_folder = $_SERVER['DOCUMENT_ROOT']. "/file_download/";
    if (is_file($files_folder.$filename))
    {
        $spliturl = explode (".", $filename);
        $file_extension = $spliturl[sizeof($spliturl)-1];
        switch(strtolower($file_extension)) {
              case "pdf": $ctype="application/pdf"; break;
              case "png": $ctype="image/png"; break;
              case "jpeg": $ctype="image/jpeg"; break;
              case "jpg": $ctype="image/jpeg"; break;
              default: $ctype = false; break;
        }
        if($ctype) {
            header("Content-Type: $ctype");
            header("Content-Disposition: $disposition; filename=".$filename);
            header("Content-Description: Download ");
            echo file_get_contents($files_folder.$filename);
        }echo "Error extension!";
    }else echo "The file does not exist!";

Upvotes: 1

Views: 3087

Answers (1)

Justinas
Justinas

Reputation: 43479

use .htaccess or PHP headers. Since i have to still allow show file in browser, but download same file on button click, i used this php code:

if(isset($_GET['file'])){
    $path = "uploads/" . $_GET['file'];
    $filename = $_GET['file'];

    if(file_exists($path)) {
        header('Content-Transfer-Encoding: binary');  // For Gecko browsers mainly
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT');
        header('Accept-Ranges: bytes');  // For download resume
        header('Content-Length: ' . filesize($path));  // File size
        header('Content-Encoding: none');
        header('Content-Type: application/pdf');  // Change this mime type if the file is not PDF
        header('Content-Disposition: attachment; filename=' . $filename);  // Make the browser display the Save As dialog
        readfile($path);  //this is necessary in order to get it to actually download the file, otherwise it will be 0Kb
    } else {
        echo "File not found on server";
    }
}else{
    echo "No file to download";
}

And calling this script:

www.example.com/downloadFile.php?file=someFile.pdf

Upvotes: 2

Related Questions