[mysql]不能下载在 linux 中使用 php 文件

发布时间: 2017/2/17 1:48:42
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.
<?php
// Make sure an ID was passed
include('include/function.php');
if(isset($_GET['id'])) {
// Get the ID
    $id = intval($_GET['id']);

    // Make sure the ID is in fact a valid ID
    if($id <= 0) {
        die('The ID is invalid!');
    }
    else {
        // Connect to the database
        $dbLink = new mysqli('localhost', 'root', 'jio', 'jio');
        if(mysqli_connect_errno()) {
            die("MySQL connection failed: ". mysqli_connect_error());
        }

        // Fetch the file information
        $query = "
            SELECT `id`,`date`,`expected_date`,`comname`,`type`,`name`,`path`,`mime`, `size`, `data`,`other_detail`,`remark`,`username`
            FROM `depository`
            WHERE `id` = {$id}";
        $result = $dbLink->query($query);

        if($result) {
            // Make sure the result is valid
            if($result->num_rows == 1) {
            // Get the row
                $row = mysqli_fetch_assoc($result);

                // Print headers

                header("Content-Type: ". $row['mime']);
                header("Content-Length: ". $row['size']);
                header("Content-Disposition: attachment; filename=". $row['name']);


            }
            else {
                echo 'Error! No image exists with that ID.';
            }

            // Free the mysqli resources
            mysqli_free_result($result);
        }
        else {
            echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
        }
        mysqli_close($dbLink);
    }
}
else {
    echo 'Error! No ID was passed.';
}
?> 

我试图从路径位置 (doc 根) 下载文件但得到一个空文件下载或损坏的文件下载。任何人都可以建议我到底错在上面的代码或使用其他任何位置。

解决方法 1:

发送标头后,您需要读取文件内容和发送数据-以下不测试但或多或少是你需要做什么。您可能需要调整 $filepath 变量的内容 $row['path'] 从 sql 结果。

if($result->num_rows == 1) {
    $row = mysqli_fetch_assoc($result);

    header("Content-Type: ". $row['mime']);
    header("Content-Length: ". $row['size']);
    header("Content-Disposition: attachment; filename=". $row['name']);

    /* you need to actually read the file and send it */

    $filepath=$row['path'] . '/' . $row['name'];
    if( !realpath( $filepath ) ) exit('Filepath '.$filepath.' is incorrect');

    if( $file = fopen( $filepath, 'rb' ) ) {
        while( !feof( $file ) and ( connection_status()==0 ) ) {
            print( fread( $file, 1024*8 ) );
            flush();
        }
        fclose( $file );
    }

}
官方微信
官方QQ群
31647020