在PHP中,readfile函数用于读取一个文件,并将其内容输出到输出缓冲区。以下是一些readfile函数的使用技巧:
- 读取并输出文件内容:
$file = "example.txt"; readfile($file);
- 下载文件:
$file = "example.txt"; header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.basename($file).'"'); readfile($file); exit;
- 设置文件下载速度:
$file = "example.txt"; $download_rate = 1000; // 1kb/s if(file_exists($file)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.basename($file).'"'); header('Content-Transfer-Encoding: binary'); header('Content-Length: ' . filesize($file)); $file = fopen($file, "r"); while(!feof($file)) { echo fread($file, $download_rate); flush(); sleep(1); } fclose($file); exit; }
- 输出文件内容到变量:
$file = "example.txt"; $content = file_get_contents($file); echo $content;