linux下php下载文件 (你怎么在Linux系统中用PHP下载文件?)
在Linux系统中用PHP下载文件的方法如下:
-
首先,创建一个下载文件的PHP脚本,例如 download.php,在脚本中指定要下载的文件。
-
在脚本中,使用header函数指定下载文件的MIME类型,并设置文件的文件名。例如,使用以下代码设置文件类型和文件名:
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="file.txt"');
- 在脚本中,使用readfile函数读取要下载的文件内容,并将其输出到浏览器中。例如:
readfile('/path/to/file.txt');
完整的代码如下:
“`
<?php
$file = '/path/to/file.txt';
$filesize = filesize($file);
$filename = basename($file);
// Set the MIME type and file name for download
header(‘Content-Type: application/octet-stream’);
header(‘Content-Disposition: attachment; filename=”‘ . $filename . ‘”‘);
// Set the file size for download
header(‘Content-Length: ‘ . $filesize);
// Read the file content and output it to the browser
readfile($file);
?>
“`
这个脚本可以下载一个名为file.txt的文件,该文件位于服务器上的/path/to目录中。浏览器会显示一个下载对话框,用户可以选择下载这个文件或取消。
总之,在Linux下PHP下载文件很简单,只需要使用header、readfile等函数即可实现。