单击提交输入按钮时如何下载 PHP 中的文件

How to download a file in PHP when clicking submit input button

我有一个带有输入提交按钮的表单,我希望它在单击按钮时下载文件。

我的 if 语句基本上只是检查文件是否存在,如果存在则开始下载文件。该部分有效,但是我无法使其正常工作,因此它仅在单击按钮时才下载文件。

目前,点击按钮时没有任何反应。

也许我没有将 if 语句放在正确的位置?

      <form action='?module=clientsupport&call=landing-proco' method='post' enctype="multipart/form-data">           
        <input type='submit' name='download' class="button yellow" value="Download"/>

        <?php
        if (file_exists("D:/wwwroot/Workspace/George/Goliath/modules/test/file.txt")) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . basename("D:/wwwroot/Workspace/George/Goliath/modules/test/file.txt") . '"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize("D:/wwwroot/Workspace/George/Goliath/modules/test/file.txt"));
            readfile("D:/wwwroot/Workspace/George/Goliath/modules/test/file.txt");
            sleep(2);
            unlink("D:/wwwroot/Workspace/George/Goliath/modules/test/file.txt");
            exit;
        }
        ?>

    </form>

看看你的程序。

第 1 行:

     <form action='?module=clientsupport&call=landing-proco' method='post' enctype="multipart/form-data">           

… 开始输出 HTML 文档。

然后你可以:

 header('Content-Description: File Transfer');

你开始输出的东西不是 HTML 文档,而是 it is too late 因为你已经 在 HTML 文档的中间.

设计你的逻辑来输出这样或那样的东西。

从 html 中删除 php 代码,使用您的 PHP 代码创建新文件,并对该文件执行表单的 link 操作。它将正常工作