David Gard
David Gard

Reputation: 12047

Force download of attachment rather than opening it automatically

I have a website that lists attachments. Clicking on these attachments result in one of two types of behaviours -

  1. The attachment opens in the same window.
  2. The attachment presents the user with a dialog to open or save the document.

Number 1 appears to only be happening with PDF's, but is there a way that I can make all attachments present the Save/Open/Cancel popup to users?

Upvotes: 2

Views: 9293

Answers (4)

The Bumpaster
The Bumpaster

Reputation: 964

I've been using this as universal mime all you have to do is pass some params:

// Check download token
if (empty($_GET['mime']) OR empty($_GET['token']))
{
    exit('Invalid download token 8{');
}

// Set operation params
$mime = filter_var($_GET['mime']);
$ext  = str_replace(array('/', 'x-'), '', strstr($mime, '/'));
$url  = base64_decode(filter_var($_GET['token']));
$name = urldecode($_GET['title']). '.' .$ext; 

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

    readfile($url);
    exit;
}

// Not found
exit('File not found 8{');

and you pass your link like this:

<a href="download.php?mime=++your file ext++&title=++ your file title ++&token=++your link to a file++">Download my file</a>

title is optional :)

Upvotes: 0

David Gard
David Gard

Reputation: 12047

Using the answer kindly provided by @HappyApe, here is the full code that I use to achieve forcing download of a document when clicking on an attachment link in Wordpress.

/**
 * Check that a page is the permalink of an attachment and force the download of the attahment if it is
 */
add_action('template_redirect', 'template_redirect');
function template_redirect(){

    global $post;

    /** Get the attachment URL as a pertty link ($url) and as a link to the file ($guid) */
    $url = get_permalink($post->ID);
    $guid = wp_get_attachment_url($post->ID);

    /** Get the file name of the attachment to output in the header */
    $file_name = basename(get_attached_file($post->ID));

    /** Get the location of the file on the server */
    $file_location = $_SERVER['DOCUMENT_ROOT'].substr($guid, strpos($guid, '/wp-content'));

    /** Get the file Mime Type */
    $finfo = new finfo;
    $mime_type = $finfo->file($file_location, FILEINFO_MIME);

    /** Check that the page we are on is a local attachment and force download if it is */
    if(is_local_attachment($url)) :

        header("Content-type: ".$mime_type, true, 200);
        header("Content-Disposition: attachment; filename=".$file_name);
        header("Pragma: no-cache");
        header("Expires: 0");

        readfile($guid); 

        exit();

    endif;

}

Upvotes: 0

TigerTiger
TigerTiger

Reputation: 10806

For the PDF only ..

// The user will receive a PDF to download
header('Content-type: application/pdf');

// File will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The actual PDF file on the server is source.pdf
readfile('source.pdf');

...

for all other file type perhaps you could use .. echo mime_content_type('Yourfile.ext') o

header('Content-type: '.mime_content_type('Yourfile.ext'));
header('Content-Disposition: attachment; filename="'.$output_filename.'"');
readfile($source_filename);

Beware that I haven't tested it...

The Content-type header specifies what type of file is to be downloaded, specified by a mime type. The Content-Disposition header specifies a new filename for the file which is to be downloaded. The readfile line is not a header being sent, but a PHP call that gets all the data from a file and outputs it. The argument you pass to the readfile function is the location of the actual pdf file to be downloaded.

UPDATE

mime_content_type() function is deprecated. you'll ned to replace with this ...

$finfo = new finfo;

$fileinfo = $finfo->file($file, FILEINFO_MIME);

Upvotes: 4

Gung Foo
Gung Foo

Reputation: 13558

you need to send the appropriate content-type headers().

Example (for pdf, but works for anything if you adjust the mimetype):

<?php
header('Content-disposition: attachment; filename=huge_document.pdf');
header('Content-type: application/pdf');   // make sure this is the correct mime-type for the file
readfile('huge_document.pdf');
?> 

Additional reading:

http://webdesign.about.com/od/php/ht/force_download.htm

Upvotes: 1

Related Questions