简体   繁体   English

PHP下载脚本无法下载上传的文件

[英]PHP download script cannot download uploaded files

I want to create a upload and download function in my website. 我想在我的网站上创建上传和下载功能。 The upload script is working but the download script is not working. 上载脚本有效,但下载脚本无效。 I am not getting any error but once the files are retrieve from the database i couldn't download it. 我没有收到任何错误,但是一旦从数据库中检索了文件,便无法下载。 If i click on the file the file content open in the same page. 如果我单击该文件,则文件内容将在同一页面中打开。

        <?php
        $query = "SELECT id, name FROM upload";
        $result = mysql_query($query) or die('Error, query failed');
        if(mysql_num_rows($result) == 0) {
            echo "Database is empty <br>";
        } else {
            while(list($id, $name) = mysql_fetch_array($result)) {
                ?>
                <a href="download.php?id=<?php echo urlencode($id);?>"><?php echo urlencode($name);?></a> <br>
                <?php
            }
        }
        mysql_close();
        ?>
    </body>
</html>
<?php
if(isset($_GET['id'])) {
    // if id is set then get the file with the id from database
    $id    = $_GET['id'];
    $query = "SELECT name, type, size, content " .
    "FROM upload WHERE id = '$id'";
    $result = mysql_query($query) or die('Error, query failed');
    list($name, $type, $size, $content) = mysql_fetch_array($result);
    header("Content-length: $size");
    header("Content-type: $type");
    header("Content-Disposition: attachment; filename=$name");
    ob_clean();
    flush();
    echo $content;
    mysql_close();
    exit;
}
?>

This is the url to the download site: download 这是下载站点的URL: 下载

You can't set any headers after output has been sent to the browser . 输出发送 到浏览器 后, 您将无法设置任何标题 This has clearly been done by the time your last lot of code is executed, because you've got HTML code above it. 显然,在您执行最后的代码时,已经完成了此操作,因为您上面已经有了HTML代码。

It should work by putting your code at the top of your script, instead of the bottom. 它应该通过将代码放在脚本的顶部而不是底部来工作。

Error wise, it sounds like you aren't getting any errors. 明智的选择,听起来您没有任何错误。 You should turn on error reporting, at the very least on your local/development environment: 您至少应在本地/开发环境中打开错误报告:

error_reporting(E_ALL);

This would likely tell you the cause of your issue straight away and help you diagnose it quickly. 这可能会立即告诉您问题的原因并帮助您快速诊断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM