在PHP中,你可以使用`header()`函数和`readfile()`函数来实现文件下载,下面是一个简单的示例代码,演示了如何下载文件:
<?php // 文件路径 $file = 'path/to/your/file.ext'; // 检查文件是否存在 if (file_exists($file)) { // 设置下载头信息 header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . basename($file) . '"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); exit; } else { echo '文件不存在'; } ?>
在上面的代码中,你需要将`$file`变量替换为你要下载的实际文件路径,代码会检查文件是否存在,并设置适当的头信息来告诉浏览器这是一个文件下载请求,使用`readfile()`函数将文件内容发送到浏览器,并通过`exit`语句终止脚本执行。
请注意,上述代码仅适用于下载本地服务器上的文件,如果你要下载远程文件,你需要使用其他方法,例如使用`curl`库或`file_get_contents()`函数来获取远程文件的内容,然后再将其发送给浏览器。
你还可以根据需要对代码进行进一步的定制,例如添加身份验证、日志记录、错误处理等功能。