PHP从服务器下载文件将打开文件而不是下载
我一直在练习在Mysql中保存文件名,并使用PHP从服务器下载文件将打开文件而不是下载,php,mysqli,Php,Mysqli,我一直在练习在Mysql中保存文件名,并使用GET方法从服务器下载文件。上传工作正常,但从文件夹下载文件时,文件会自动打开,不会下载。 这是我从文件夹下载文件的代码 <?php include 'includes/ann.php'; // connect to the database $username = "uname"; $password = "pass"; $database = "practice5"; $servername = "localhost"; // Creat
GET
方法从服务器下载文件。上传工作正常,但从文件夹下载文件时,文件会自动打开,不会下载。
这是我从文件夹下载文件的代码
<?php
include 'includes/ann.php';
// connect to the database
$username = "uname";
$password = "pass";
$database = "practice5";
$servername = "localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM documents";
$result = mysqli_query($conn, $sql);
$myfile = mysqli_fetch_all($result, MYSQLI_ASSOC);
// Downloads files
if (isset($_GET['docum_id'])) {
$ids = $_GET['docum_id'];
// fetch file to download from database
$sql = "SELECT * FROM documents WHERE id=$ids";
$result = mysqli_query($conn, $sql);
$file = mysqli_fetch_assoc($result);
$filepath = 'docs/' . $file['name'];
if (file_exists($filepath)) {
ob_start();
header('Content-Description: File Transfer');
header('Content-Type: application/octetstream');
header("Content-Transfer-Encoding: Binary");
header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate,post-check=0, pre-check=0');
header('Content-Type: application/force-download');
header('Pragma: public');
header('Content-Length: ' . filesize('docs/' . $file['name']));
ob_clean();
flush();
readfile('docs/' . $file['name']);
exit();
}
else
{
echo "No files found";
}
}
?>
<div style="margin-top: 100px;" class="container">
<div class="row">
<div class="col-lg-8 mx-auto">
<h2 style="text-align: center">Download</h2>
<table id="example" class="table table-bordered">
<thead>
<tr class="bg-warning">
<th><?php echo $lang['tableheadOne']?></th>
<th><?php echo $lang['murtiletit']?></th>
<th><?php echo $lang['murtiledesc']?></th>
</tr>
</thead>
<tbody>
<?php foreach ($myfile as $file): ?>
<tr>
<td><?php echo $file['id']; ?></td>
<td><?php echo $file['title']; ?></td>
<td><?php echo $file['description']; ?>
<a href="checkFile.php?docum_id=<?php echo $file['id'] ?>"><?php echo $lang['download']?></a></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
</div>
</div>
</div
..footer
将下载属性添加到链接
<a href="checkFile.php?docum_id=<?php echo $file['id'] ?>" download><?php echo $lang['download']?></a>
它会告诉浏览器加载而不是打开,我认为,您可以在link中提供文件路径,并将文件保存在公共文件夹中。如果您不需要生成文件或更改文件,只需将链接路径设置为文件。我不认为,您需要在脚本中使用标题。@Minatula Shakhbazov如果我有多个文件怎么办?公开路径安全吗?根据我的经验:通常用于下载的文件放在公共文件夹中(例如,上传,与css文件的情况相同,它们存储在公共文件夹中)。从这个文件夹中,您可以通过直接链接下载文件,在您的页面上,您可以生成带有这些文件路径的链接。我没有尝试多次下载(不确定该浏览器是否允许您下载)。您的代码易受SQL注入攻击。你应该使用事先准备好的陈述。