5

我正在从原始二进制数据创建一个 PDF 文件,它运行良好,但由于我在我的 PHP 文件中定义的标题,它会提示用户“保存”文件或“打开方式”。有什么办法可以将文件保存在本地服务器上的某个地方http://localhost/pdf吗?

以下是我在页面中定义的标题

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: application/pdf");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Transfer-Encoding: binary");
4

2 回答 2

10

如果您想将文件保存在服务器上而不是让访问者下载它,则不需要标题。标头用于告诉客户您要发送的内容,在这种情况下什么都不是(尽管您可能会显示一个链接到您新创建的 PDF 或其他内容的页面)。

因此,只需使用诸如file_put_contents在本地存储文件之类的功能,最终让您的 Web 服务器处理文件传输和 HTTP 标头。

// Let's say you have a function `generate_pdf()` which creates the PDF,
// and a variable $pdf_data where the file contents are stored upon creation
$pdf_data = generate_pdf();

// And a path where the file will be created
$path = '/path/to/your/www/root/public_html/newly_created_file.pdf';

// Then just save it like this
file_put_contents( $path, $pdf_data );

// Proceed in whatever way suitable, giving the user feedback if needed 
// Eg. providing a download link to http://localhost/newly_created_file.pdf
于 2012-02-15T13:00:48.940 回答
0

您可以使用输出控制功能。将 ob_start() 放在脚本的开头。最后使用 ob_get_contents() 并将内容保存到本地文件。

之后,您可以使用 ob_end_clean() 或 ob_end_flush() ,具体取决于您是否也想将 PDF 输出到浏览器,或者将用户重定向到其他页面。如果您使用 ob_end_flush() 确保在刷新数据之前设置标题。

于 2012-02-15T13:06:26.787 回答