0

我有用于从 mysql 数据库下载文件的 PHP 代码。我试图将我的下载缓冲到每个块 1024 的块中。但它看起来 fopen 无法从它给出错误的数据库中打开我的文件。

Warning: fclose() expects parameter 1 to be resource, boolean given in /var/www/html/download/get_file_work.php on line 40

如何使用 fopen 函数打开数据库中的文件。

我的php代码

<?php
ob_start();
$company = $_GET['company'];
if(isset($_GET['id']))
  {
    $id = intval($_GET['id']);
    if($id <= 0)
      {
        die('The ID is invalid!');
      }
    else
      {
        $dbLink = new mysqli('localhost', 'sqldata', 'sqldata', 'balhaf');
        if(mysqli_connect_errno())
          {
            die("MySQL connection failed: ". mysqli_connect_error());
          }
        $query = "SELECT mime, name, size, data FROM $company WHERE id = $id";
        $result = $dbLink->query($query);
        if($result)
          {
            if($result->num_rows == 1) {
              $row = mysqli_fetch_assoc($result);
              $size = $row['size'];
              $filename = $row['name'];
              $data = $row['data'];
              $mime = $row['mime'];
              if ($fd = fopen ($data, "r")) {
                ini_get('zlib.output_compression');
                ini_set('zlib.output_compression', 'Off');
                header('Content-Type: application/pdf');
                while (@ob_end_clean());
                header('Content-Disposition: attachment; filename='.($filename));
                header('Content-Length:'.($size));
                while(!feof($fd)) {
                  $buffer = fread($fd, 1024);
                  echo $buffer;
                }
              }
              fclose ($fd);
              exit;
            }
            else
              {
                echo 'Error! No image exists with that ID.';
              }
            mysqli_free_result($result);
          }
        else
          {
            echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
          }
        mysqli_close($dbLink);
      }
  }
else
  {
    echo 'Error! No ID was passed.';
  }
?>
4

1 回答 1

1

如果$data只是二进制数据,则不能fopen在其上使用。 fopen仅适用于文件名字符串。事实上,没有必要读取数据块,因为$data显然已经拥有了所有数据。你可以这样做:

// other headers
header('Content-Length:'.($size));
echo $data;
exit;
于 2013-09-13T22:52:11.717 回答