How can PHP developers optimize their code to prevent memory-related errors during file uploads?
PHP developers can optimize their code to prevent memory-related errors during file uploads by increasing the memory limit in the php.ini configuration file, using functions like `ini_set('memory_limit', '256M');` before the file upload process, and handling file uploads in chunks rather than loading the entire file into memory at once.
// Set memory limit to 256MB
ini_set('memory_limit', '256M');
// Handle file upload in chunks
$chunkSize = 1024 * 1024; // 1MB chunk size
$filePath = 'path/to/uploaded/file';
$handle = fopen($filePath, 'rb');
while (!feof($handle)) {
$chunk = fread($handle, $chunkSize);
// Process the chunk here
}
fclose($handle);