1

I am making a wallpapers page on my WordPress website. I would like for the image to download onto user's hard drive when he clicks on it. This is what I have so far:

<a href="download.php?file=/path/to/image">
    <img src="/path/to/image" />
</a>

My download.php script is as follows (source: href image link download on click):

$file = $_GET['file'];

if (headers_sent()) {
    die('Headers Sent');
}

if (file_exists($file)) {

    // Parse Info / Get Extension
    $fsize = filesize($file);
    $path_parts = pathinfo($file);
    $ext = strtolower($path_parts["extension"]);

    // Determine Content Type
    switch ($ext) {
        case "gif": $ctype="image/gif"; break;
        case "png": $ctype="image/png"; break;
        case "jpeg":
        case "jpg": $ctype="image/jpg"; break;
        default: die('Wrong Extension');
    }

    header("Pragma: public"); // required
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private", false); // required for certain browsers
    header("Content-Type: $ctype");
    header("Content-Disposition: attachment; filename=\"".basename($file)."\";" );
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . $fsize);
    ob_clean();
    flush();
    readfile($file);

} else {
    die('File Not Found');
}

However, when I click on the image, WordPress realizes there's no template for download.php and redirects me to home page. What am I doing wrong?

UPDATE: As far as I can see, this cannot be done like this and any ajax call in WordPress has to go through admin-ajax.php

Community
  • 1
  • 1
Banana
  • 4,010
  • 9
  • 33
  • 49
  • 2
    I cannot answer the wordpress part of this, but please make sure you protect against downloading any file on your filesystem, which is currently possible. You should check that `$_GET['file']` is not the full path, but rather relative to the base path in which your images are stored. Then you also need to protect against directory traversal, blocking `../` so it isn't possible to put in `?file=../../../../../../../../etc/passwd` for example, or a WP file holding database credentials... – Michael Berkowski Jun 05 '13 at 13:58

1 Answers1

0

You can use the following code

<a href="<?php echo home_url() ?>download-image.php?file=/path/to/image">
    <img src="/path/to/image" />
</a>
andrewsi
  • 10,807
  • 132
  • 35
  • 51
  • And where should my download.php file be? Now it's in the theme's root folder, but it's not being called. – Banana Jun 05 '13 at 14:55