我有从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.';
}
?>
答案 0 :(得分:1)
如果$data
只是二进制数据,则不能在其上使用fopen
。 fopen
仅适用于文件名字符串。事实上,不需要读取数据块,因为$data
显然已经拥有了所有数据。你可以这样做:
// other headers
header('Content-Length:'.($size));
echo $data;
exit;