PHP file_get_contents 对于超过 20 MB 的 pdf 文件给出内存不足问题

问题描述 投票:0回答:1
ini_set('memory_limit', '-1');
ini_set('post_max_size','-1');
ini_set('upload_max_filesize','-1');
ini_set('max_execution_time','0');
set_time_limit(0);

$files = file_get_contents($_FILES['file']['tmp_name']);
$file_base = base64_encode($files);

上面的代码对于小于 20 MB 的文件运行良好。但是当我尝试上传大于 20MB 的 pdf 文件时,它显示内存不足问题,如下所示。

Out of memory (allocated 439840768) (tried to allocate 116729376 bytes)

我需要将 pdf 文件以 blob 格式存储在 MySQL 数据库中,而不将其保存在文件夹或某个位置。

我更改了 php.ini 文件中的所有设置以增加内存限制、上传最大大小和执行时间,但没有用。

我已经检查了 stackoverflow 和其他一些域中的所有解决方案,但没有找到有用的答案。

php mysql file-get-contents
1个回答
0
投票
Reading a large file into memory using file_get_contents can indeed cause memory issues, even if you set the memory limit to unlimited. It's not recommended to load very large files entirely into memory.

For handling large files, especially with file_get_contents, it's better to read the file in chunks. Here's an example of how you can read a file in chunks:

// Set a reasonable buffer size (e.g., 8 MB)
$bufferSize = 8 * 1024 * 1024;

$fileHandle = fopen($_FILES['file']['tmp_name'], 'rb');


$fileContent = '';

while (!feof($fileHandle)) {
    $fileContent .= fread($fileHandle, $bufferSize);
}

fclose($fileHandle);

// Now you can base64 encode the content
$file_base = base64_encode($fileContent);

Note : Please set buffer size as per your requirement.
© www.soinside.com 2019 - 2024. All rights reserved.