首页 > 解决方案 > PHP从服务器下载文件打开文件而不是下载

问题描述

我一直在练习在 Mysql 中保存文件名并使用该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

上面的代码在本地主机上运行良好,但在服务器上它不起作用,只要我单击下载按钮,它就会打开损坏的文件。谢谢

标签: phpmysqli

解决方案


将下载属性添加到链接

<a href="checkFile.php?docum_id=<?php echo $file['id'] ?>" download><?php echo $lang['download']?></a>

它会告诉浏览器加载而不是打开


推荐阅读