What are the best practices for handling timeouts in PHP scripts that involve large data imports?
When handling timeouts in PHP scripts that involve large data imports, it is important to increase the maximum execution time and memory limit to prevent the script from timing out prematurely. Additionally, breaking down the import process into smaller chunks and utilizing error handling mechanisms can help in managing the import efficiently.
// Increase maximum execution time and memory limit
ini_set('max_execution_time', 300); // 5 minutes
ini_set('memory_limit', '512M');
// Import large data in chunks
$chunkSize = 1000;
$totalRows = count($data);
for ($i = 0; $i < $totalRows; $i += $chunkSize) {
$chunk = array_slice($data, $i, $chunkSize);
// Process the chunk
foreach ($chunk as $row) {
// Import data
}
}