[英]How to download a file from specific directory using php header
我有一些代码可以使用php标头下载文件,但无法正常工作,并且想添加目录以进行读取
<?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>";
}
?>
显示错误内容错误
该文件不存在!
我在用
此链接下载文件的文件原始位置为
首先, $file = '$var_1';
的引号$file = '$var_1';
不会得到正确的解释,
因此它需要读为$file = $var_1;
您也缺少右括号}
<?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
?>
您提到要使用其他文件夹。
您可以使用以下效果:
$dir = "folder/"; // trailing slash is important
$file = $dir . $var_1;
要么
$dir = "../folder/"; // trailing slash is important
$file = $dir . $var_1;
取决于文件夹的位置。
以下内容已为我测试和工作,并且文件是从服务器的根目录运行的。
<?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 (我以PDF文件为例)
<a href="download.php?link=document.pdf">Download here</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.