欢迎各位兄弟 发布技术文章
这里的技术是共享的
<?php error_reporting(E_ALL); ini_set("display_errors", "1"); // shows all errors // ini_set("display_start_errors", "1"); // shows all errors // "display_startup_errors" ini_set("log_errors", "on"); ini_set("error_log", "php_errorccc.log"); // 文件路径 $file = $_GET['file']; if(!(strpos($file, 'tmp')===0)){ //限制必须 tmp 目录下的,或 tmp 开头的文件 die(" 下载路径不对,下载文件路径必须经 tmp 开头"); } // 确保文件存在 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)); // 读取文件并输出到浏览器 readfile($file); exit; } else { // 文件不存在时返回404错误 header("HTTP/1.0 404 Not Found"); echo 'File not found'; } ?> 报错 <br /> <b>Fatal error</b>: Allowed memory size of aaaa bytes exhausted (tried to allocate 279334912 bytes) in <b>/www/web/jsfaq_luxshare-ict_com/public_html/download.php</b> on line <b>29</b><br />
这个错误表示 PHP 脚本在尝试读取并输出文件时,耗尽了 PHP 配置的内存限制。默认情况下,PHP 的内存限制是 128M
(即 134217728 字节),但您的脚本尝试分配的内存超过了这个限制。
增加 PHP 内存限制: 您可以通过在脚本中增加内存限制来解决这个问题。在脚本的开头添加以下代码:
php
ini_set('memory_limit', '512M'); // 将内存限制增加到 512M
这将允许脚本使用更多的内存。您可以根据文件的实际情况调整这个值。
分段读取文件: 如果文件非常大,直接将整个文件读入内存可能会导致内存耗尽。您可以使用分段读取文件的方式来避免这个问题。以下是一个示例:
php
$file = $_GET['file']; if(!(strpos($file, 'tmp')===0)){ //限制必须 tmp 目录下的,或 tmp 开头的文件 die(" 下载路径不对,下载文件路径必须经 tmp 开头"); } 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)); // 打开文件 $handle = fopen($file, 'rb'); if ($handle === false) { die('Unable to open file'); } // 逐块读取文件并输出 while (!feof($handle)) { echo fread($handle, 8192); // 每次读取 8KB ob_flush(); flush(); } // 关闭文件 fclose($handle); exit; } else { header("HTTP/1.0 404 Not Found"); echo 'File not found'; }
检查文件大小: 在读取文件之前,您可以检查文件的大小,并根据文件大小决定是否增加内存限制或使用分段读取的方式。
php
$file = $_GET['file']; if(!(strpos($file, 'tmp')===0)){ //限制必须 tmp 目录下的,或 tmp 开头的文件 die(" 下载路径不对,下载文件路径必须经 tmp 开头"); } if (file_exists($file)) { $filesize = filesize($file); if ($filesize > 100 * 1024 * 1024) { // 如果文件大于 100MB ini_set('memory_limit', '512M'); // 增加内存限制 } 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); // 读取文件并输出到浏览器 readfile($file); exit; } else { header("HTTP/1.0 404 Not Found"); echo 'File not found'; }
通过这些方法,您应该能够解决内存耗尽的问题,并成功下载大文件。