How can PHP handle large file uploads more efficiently to avoid timeouts?
When uploading large files, PHP may encounter timeouts due to the default settings in php.ini. To handle large file uploads more efficiently and avoid timeouts, you can increase the maximum execution time, memory limit, and upload size in php.ini. Additionally, you can use techniques like chunked uploading or streaming to process large files in smaller parts.
// Increase maximum execution time, memory limit, and upload size
ini_set('max_execution_time', 300); // 5 minutes
ini_set('memory_limit', '256M');
ini_set('upload_max_filesize', '100M');
// Process large file upload using chunked uploading or streaming
// Example: uploading a file in chunks using fopen, fread, and fwrite
$targetFile = 'uploads/' . $_FILES['file']['name'];
$chunkSize = 1 * 1024 * 1024; // 1MB chunk size
$handle = fopen($_FILES['file']['tmp_name'], 'rb');
$target = fopen($targetFile, 'ab');
while (!feof($handle)) {
fwrite($target, fread($handle, $chunkSize));
}
fclose($handle);
fclose($target);
Related questions
-
SQL injection data validation prepared statements
-
mysqli_query syntax function
-
IF statement PHP MySQL commands