Reputation: 37
I have some code to download file using php header but it is not properly working and want to add directory to read
<?php
if(isset($_GET['link'])){
$var_1 = $_GET['link'];
$dir='/upload/';
}
?>
<?php
if(isset($_GET['link'])){
$var_1 = $_GET['link'];
$file = $var_1;
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
echo "<h1>Content error</h1><p>The file does not exist!</p>";
}
?>
It shows error Content error
The file does not exist!
I am Using
this link to download the file file original location is
Upvotes: 2
Views: 44845
Reputation: 74217
First, the quotes in $file = '$var_1';
won't get interpreted correctly,
therefore it needs to read as $file = $var_1;
You also have a missing closing brace }
<?php
if(isset($_GET['link']))
{
$var_1 = $_GET['link'];
$file = $var_1;
if (file_exists($file))
{
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
} //- the missing closing brace
?>
And you mentioned that you wanted to use a different folder.
You could use something to the effect of:
$dir = "folder/"; // trailing slash is important
$file = $dir . $var_1;
or
$dir = "../folder/"; // trailing slash is important
$file = $dir . $var_1;
depending on the folder's location.
The following is tested and worked for me and the files were run from the root of my server.
<?php
if(isset($_GET['link']))
{
$var_1 = $_GET['link'];
// $file = $var_1;
$dir = "folder/"; // trailing slash is important
$file = $dir . $var_1;
if (file_exists($file))
{
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
} //- the missing closing brace
?>
HTML (I used a PDF file as an example)
<a href="download.php?link=document.pdf">Download here</a>
Upvotes: 13