Dar*_*ife 8 php database oop header-files
我正试图通过我的数据库中的标题下载文件.当我将下载代码更改为使用OOP的下载代码时,我不确定为什么我下载的文件全部损坏但是当我的代码是非OOP时这样做很好.
这是我获取文件ID并调用下载函数的地方:(handleDownload.php)
if (isset($_GET['id'])) {
$id = $_GET['id'];
//pump id into function getDBFiles to pull file with matching id
$fileData = $Download->getDBFiles($id);
header('Content-Type:"' . $fileData[2]. '"');
header('Content-Disposition: attachment; filename="' . $fileData[1]. '"');
echo $fileData[0];
exit;
}
Run Code Online (Sandbox Code Playgroud)
这是从数据库中提取文件的函数(download.php)
public function getDBFiles($id) {
global $database;
$sql = "SELECT * FROM ".self::$table_name." WHERE resume_id ='" . $id . "'";
$result = $database->query($sql);
if ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$name = $row['resume_title'];
$type = $row['file_type'];
$content = $row['resume_data']; //content of file
//$size = $row['file_size']; //file size
return array($content, $name, $type);
}
}
$Download = new Download();
$download =& $Download;
Run Code Online (Sandbox Code Playgroud)
如果代码全部在一个页面中,如下所示,代码工作正常:
if (isset($_GET['id'])) {
$id = $_GET['id'];
mysqli_select_db($con, "apples");
$query = "SELECT * FROM resume where resume_id ='" . $id . "'";
$result = mysqli_query($con, $query) or die('Error, query failed');
if ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$name = $row['resume_title'];
$type = $row['file_type'];
$content = $row['resume_data']; //content of file
$size = $row['file_size']; //file size
header('Content-Type:"' . $type . '"');
//header('Content-length:"' . $size . '"');
header('Content-Disposition: attachment; filename="' . $name . '"');
//var_dump($row);
echo $content;
}
}
Run Code Online (Sandbox Code Playgroud)
更新:我现在得到的下载文件已损坏,而不是空白文件.这是不同下载代码输出相同文件的方式.顶部的一个来自OOP代码,而另一个来自工作的非OOP版本.

这是我的完整下载代码.
try {
//execute retrieval of files from database
$Download-> showDBFiles();
//pass results to output array
$output = $Download->getMessages();
//if id is set then get file from database
if (isset($_GET['id'])) {
$id = $_GET['id'];
//pump id into function getDBFiles to pull file with matching id
$fileData = $Download->getDBFiles($id);
header('Content-Type:"' . $fileData[2]. '"');
header('Content-Disposition: attachment; filename="' . $fileData[1]. '"');
echo $fileData[0];
die();
}
} catch (Exception $e) {
$result[] = $e->getMessages();
}
Run Code Online (Sandbox Code Playgroud)
调用函数后,我会用foreach循环回显输出(下载链接)
<h2>Output</h2>
<?php if ($output) { ?>
<ul class="result">
<?php
foreach ($output as $message) {
$id = $message['id'];
$name = $message['name'];
?>
<li><a href="handleDownload.php?id=<?php echo $id; ?>"><?php echo $name; ?></a></li>
<?php }
?>
</ul>
Run Code Online (Sandbox Code Playgroud)
在非 OOP 解决方案中,检查 php 文件内的前导空格。
由于前导空格,以下代码将生成损坏的文件。
<?php
if (isset($_GET['id'])) {...
Run Code Online (Sandbox Code Playgroud)
这也适用于 php 结束标记后的空格(您不应该使用)。
这些字符将由您的浏览器提交,包含在下载流中并损坏整个文件。