prasadmsvs February 2016

How to Create a file download link in a page template

I need to download a file on click of a link in word press. I have file url. I know the download code in php and I added in functions.php.

function downloadFile($f){
    header('Content-Disposition: attachment; filename=' . urlencode($f));
    header('Content-Type: application/force-download');
    header('Content-Type: application/octet-stream');
    header('Content-Type: application/download');
    header('Content-Description: File Transfer');
    header('Content-Length: ' . filesize($f));
    echo file_get_contents($f);
}

Now how to call this function on click of a link? What will be the "href" of the link

Answers


Ben February 2016

On the page with the link:

<a href="download.php?f=foo">Download "Foo"</a>

On download.php (or whatever name you choose):

include "functions.php";
downloadFile($_GET["f"]);
exit;

Edit Or just create a download.php page:

<?php
    if(isset($_GET["f"])){
        $f = $_GET["f"];
        header('Content-Disposition: attachment; filename='.urlencode($f));
        header('Content-Type: application/force-download');
        header('Content-Type: application/octet-stream');
        header('Content-Type: application/download');
        header('Content-Description: File Transfer');
        header('Content-Length: ' . filesize($f));
        echo file_get_contents($f);
    }
    exit;
?>

Post Status

Asked in February 2016
Viewed 3,062 times
Voted 12
Answered 1 times

Search




Leave an answer