OM The Eternity
OM The Eternity

Reputation: 16244

How to force a file to download in PHP

I have list of images and I want a "Download" link along with every image so that user can download the image.

so can someone guide me How to Provide Download link for any file in php?

EDIT

I want a download panel to be displayed on clicking the download link I dont want to navigate to image to be displayed on the browser

Upvotes: 7

Views: 34893

Answers (4)

debugger
debugger

Reputation: 444

In HTML5 download attribute of <a> tag can be used:

echo '<a href="path/to/file" download>Download</a>';

This attribute is only used if the href attribute is set.

There are no restrictions on allowed values, and the browser will automatically detect the correct file extension and add it to the file (.img, .pdf, .txt, .html, etc.).

Read more here.

Upvotes: 4

John Parker
John Parker

Reputation: 54445

If you want to force a download, you can use something like the following:

<?php
    // Fetch the file info.
    $filePath = '/path/to/file/on/disk.jpg';

    if(file_exists($filePath)) {
        $fileName = basename($filePath);
        $fileSize = filesize($filePath);

        // Output headers.
        header("Cache-Control: private");
        header("Content-Type: application/stream");
        header("Content-Length: ".$fileSize);
        header("Content-Disposition: attachment; filename=".$fileName);

        // Output file.
        readfile ($filePath);                   
        exit();
    }
    else {
        die('The provided file path is not valid.');
    }
?>

If you simply link to this script using a normal link the file will be downloaded.

Incidentally, the code snippet above needs to be executed at the start of a page (before any headers or HTML output had occurred.) Also take care if you decide to create a function based around this for downloading arbitrary files - you'll need to ensure that you prevent directory traversal (realpath is handy), only permit downloads from within a defined area, etc. if you're accepting input from a $_GET or $_POST.

Upvotes: 35

Chris Harrison
Chris Harrison

Reputation: 5858

You can do this in .htaccess and specify for different file extensions. It's sometimes easier to do this than hard-coding into the application.

<FilesMatch "\.(?i:pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

By the way, you might need to clear browser cache before it works correctly.

Upvotes: 0

Buzogany Laszlo
Buzogany Laszlo

Reputation: 941

The solution is easier that you think ;) Simple use:

header('Content-Disposition: attachment');

And that's all. Facebook for example does the same.

Upvotes: 2

Related Questions