php download file – How to Download a File in PHP?

php download file – You can force images, exe, zip, pdf, doc, text, audio or other kind of files to download directly to the user’s hard drive using the PHP readfile() function.

php download file

php download file – The readfile() function is used in PHP script to forcibly download any file of the current location, or the file with the file path.

How to force file download with PHP?

Example

$file_url = 'http://www.your-domain-name.com/doc.pdf';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($file_url); 

How to Download a File in PHP?

savefile.html

<html>
<head>
<title>Download Files</title>
</head>
<body>
<p><a href="savefile.php?path=pakainfo.txt">Click To Download TEXT file</a></p>
<p><a href="savefile.php?path=welcome.zip">Click To Download ZIP file</a></p>
<p><a href="savefile.php?path=tamilrokers.pdf">Click To Download PDF file</a></p>
<p><a href="savefile.php?path=hdhub.jpg">Click To Download JPG file</a></p>
</body>
</html>

Example(savefile.php)

<?php

if(isset($_GET['path']))
{

$filename = $_GET['path'];

if(file_exists($filename)) {


header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Cache-Control: no-cache, must-revalidate");
header("Expires: 0");
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Content-Length: ' . filesize($filename));
header('Pragma: public');


flush();


readfile($filename);

die();
}
else{
echo "Sorry, File does not exist.";
}
}
else
echo "Sorry, Filename is not defined."
?>

Download File with File Path

savefile.html

<html>
<head>
<title>Download Files</title>
</head>
<body>
<p><a href="savefile.php?path=savefiles/tamilrokers.pdf">Download PDF file</a></p>
<p><a href="savefile2.php?path=savefiles/products.jpg">Download JPG file</a></p>
</body>
</html>

savefile2.php

<?php
if(isset($_GET['path']))
{
$url = $_GET['path'];

clearstatcache();


if(file_exists($url)) {

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($url).'"');
header('Content-Length: ' . filesize($url));
header('Pragma: public');


flush();


readfile($url,true);
die();
}
else{
echo "Sorry, File path does not exist.";
}
}
echo "Sorry,  File path is not defined."

?>

Don’t Miss : Download File From URL Using PHP?

I hope you get an idea about php download file.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.