我有一个需要进行Base64编码的文件,其大小为418 MB,但是我一直收到内存限制错误。我已经在php.ini文件中设置了memory_limit=2048M
,但我仍无法使用x86 CLI版本的PHP将其读入内存作为Base64字符串。
PHP脚本
<?php
echo "\r\n";
echo "\r\nMemory Usage\r\n" . memory_get_usage(false) . " Bytes\r\nReal " . memory_get_usage(true) . " Bytes\r\n";
echo "\r\nPeak Memory Usage\r\n" . memory_get_peak_usage(false). " Bytes\r\nReal " . memory_get_peak_usage(true) . " Bytes\r\n";
echo "\r\nMemory Limit\r\n" . ini_get('memory_limit') . "\r\n";
$file = file_get_contents('C:\Path\To\File');
echo "\r\n";
echo "\r\nMemory Usage\r\n" . memory_get_usage(false) . " Bytes\r\nReal " . memory_get_usage(true) . " Bytes\r\n";
echo "\r\nPeak Memory Usage\r\n" . memory_get_peak_usage(false). " Bytes\r\nReal " . memory_get_peak_usage(true) . " Bytes\r\n";
echo "\r\nMemory Limit\r\n" . ini_get('memory_limit') . "\r\n";
$encodedFile = base64_encode($file);
echo "\r\n";
echo "\r\nMemory Usage\r\n" . memory_get_usage(false) . " Bytes\r\nReal " . memory_get_usage(true) . " Bytes\r\n";
echo "\r\nPeak Memory Usage\r\n" . memory_get_peak_usage(false). " Bytes\r\nReal " . memory_get_peak_usage(true) . " Bytes\r\n";
echo "\r\nMemory Limit\r\n" . ini_get('memory_limit') . "\r\n";
?>
运行该脚本会产生以下结果。
PS C:\> php .\MemoryIssueTest.php
Memory Usage
382184 Bytes
Real 2097152 Bytes
Peak Memory Usage
422256 Bytes
Real 2097152 Bytes
Memory Limit
2048M
Memory Usage
447075680 Bytes
Real 448790528 Bytes
Peak Memory Usage
447084280 Bytes
Real 448790528 Bytes
Memory Limit
2048M
VirtualAlloc() failed: [0x00000008] Not enough memory resources are available to process this command.
VirtualAlloc() failed: [0x00000008] Not enough memory resources are available to process this command.
PHP Fatal error: Out of memory (allocated 448790528) (tried to allocate 593015064 bytes) in C:\MemoryIssueTest.php on line 14
PHP Stack trace:
PHP 1. {main}() C:\MemoryIssueTest.php:0
PHP 2. base64_encode() C:\MemoryIssueTest.php:14
Fatal error: Out of memory (allocated 448790528) (tried to allocate 593015064 bytes) in C:\MemoryIssueTest.php on line 14
Call Stack:
0.4046 382152 1. {main}() C:\MemoryIssueTest.php:0
33.4669 447075680 2. base64_encode() C:\MemoryIssueTest.php:14
在升级到64位的PHP版本后,我从同一脚本中得到以下结果。
PS C:\> php .\MemoryIssueTest.php
Memory Usage
402088 Bytes
Real 2097152 Bytes
Peak Memory Usage
444160 Bytes
Real 2097152 Bytes
Memory Limit
2048M
Memory Usage
440804144 Bytes
Real 442499072 Bytes
Peak Memory Usage
440812824 Bytes
Real 442499072 Bytes
Memory Limit
2048M
Memory Usage
1025909576 Bytes
Real 1027604480 Bytes
Peak Memory Usage
1025909760 Bytes
Real 1027604480 Bytes
Memory Limit
2048M
据我了解,x86应用程序应该能够消耗超过1GB的内存。那么,PHP的x86版本是否硬编码为仅允许少于1GB的内存?如果不是,请问为什么当我只需要消耗1GB但有2GB的限制时,却会出现“PHP致命错误:内存不足”的错误?
memory_limit
设置为-1
,让 x86 版本使用所需的内存,它是否能正确运行? - Dave