What is the recommended approach for handling file uploads in PHP to avoid timeouts?
When handling file uploads in PHP, one common issue is timeouts when uploading large files. To avoid timeouts, you can increase the maximum execution time and memory limit in your PHP configuration. Additionally, you can use chunked file uploads to break the file into smaller parts and upload them sequentially.
// Increase maximum execution time and memory limit
ini_set('max_execution_time', 300); // 5 minutes
ini_set('memory_limit', '128M');
// Handle chunked file uploads
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_FILES['file'])) {
$file = $_FILES['file'];
$chunk = isset($_POST['chunk']) ? $_POST['chunk'] : 0;
$totalChunks = isset($_POST['total_chunks']) ? $_POST['total_chunks'] : 1;
$uploadPath = 'uploads/';
$fileName = $file['name'];
$tmpName = $file['tmp_name'];
$targetFile = $uploadPath . $fileName . '_' . $chunk;
move_uploaded_file($tmpName, $targetFile);
if ($chunk == $totalChunks - 1) {
// All chunks uploaded, combine them into the final file
// Do additional processing here
}
}
Keywords
Related Questions
- What is the purpose of the PHP function ftp_fget in the given code snippet?
- What considerations should be made when handling email addresses with special characters in both the local part and domain part using PHP functions like idn_to_ascii()?
- What are the best practices for handling non-logged in users when using session_start() in PHP?