php 先写文件 再下载 (php先写文件再下载有什么方法?)
在网页应用程序的开发过程中,经常会遇到需要将某些文件下载到客户端的需求,比如下载附件等。而在PHP中,有一个比较常用的方法是先写文件再下载。
那么,PHP先写文件再下载有什么方法呢?
- 使用fopen和fwrite函数
使用fopen函数打开文件并以写入模式打开,使用fwrite函数向文件中写入数据。当数据写入完成后,关闭文件,然后使用header函数设置Content-Disposition和Content-Type头部信息,让浏览器开始下载文件。以下是示例代码:
“`php
$file = “filename.txt”;
$handle = fopen($file, ‘w’) or die(“无法打开文件”);
$data = “你好,世界”;
fwrite($handle, $data);
fclose($handle);
header(‘Content-Description: File Transfer’);
header(‘Content-Type: application/octet-stream’);
header(‘Content-Disposition: attachment; filename=’.basename($file));
header(‘Content-Transfer-Encoding: binary’);
header(‘Expires: 0’);
header(‘Cache-Control: must-revalidate’);
header(‘Pragma: public’);
header(‘Content-Length: ‘ . filesize($file));
readfile($file);
“`
- 使用fileputcontents函数
使用fileputcontents函数将数据写入文件,然后使用header函数设置Content-Disposition和Content-Type头部信息,让浏览器开始下载文件。以下是示例代码:
“`php
$file = “filename.txt”;
$data = “你好,世界”;
fileputcontents($file, $data);
header(‘Content-Description: File Transfer’);
header(‘Content-Type: application/octet-stream’);
header(‘Content-Disposition: attachment; filename=’.basename($file));
header(‘Content-Transfer-Encoding: binary’);
header(‘Expires: 0’);
header(‘Cache-Control: must-revalidate’);
header(‘Pragma: public’);
header(‘Content-Length: ‘ . filesize($file));
readfile($file);
“`
以上就是PHP先写文件再下载的两种常用方法,可以根据实际情况选择适合自己的方法。