Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download a file on clicking the name of file using PHP?

I Have a list of information in which there is a field where name of file is hyperlinked. I want the user to download that particular file when he clicks on it.

so, How to download a file on clicking the name of file using PHP?

I tried it using ajax whose code is as below, but I do not get any file downloaded.

download.php

$filename = $_GET['val'];
         // Fetch the file info.
 $filePath = $_SERVER['DOCUMENT_ROOT'] . "/dfms/images/docs/".$filename;

    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.');
    }

javascript function

<script>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP");  } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest();          } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};
function download(path,val) {
var req = Inint_AJAX();
req.open("GET", path+"download.php?val="+val); //make connection
//req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
req.send(null); //send value
req.onreadystatechange = function () {
 if (req.readyState==4) {
      if (req.status==200) {

      }
 }
};

}
</script>

link to download

<a href="javascript:download('http://localhost/project/images/','DMS.doc');">DMS.doc</a>
like image 388
OM The Eternity Avatar asked Dec 23 '10 12:12

OM The Eternity


People also ask

How do I force a download when I click on a link?

In most browsers, clicking on the link will open the file directly in the browser. But, if you add the download attribute to the link, it will tell the browser to download the file instead. The download attribute works in all modern browsers, including MS Edge, but not Internet Explorer.

How do you change a file name while downloading?

you can enable downloads different path option in your browser. Then you can rename the file name using typeinto activity to type the path with new filename during the execution.


1 Answers

so, How to download a file on clicking the name of file using PHP?

The easiest way should be linking to it.

<a href="download.php?......" target="_blank">DMS.doc</a>
like image 174
Pekka Avatar answered Oct 03 '22 06:10

Pekka