PHP – Stop Script Execution After Specific Time Limit

Do you have a long-running PHP script or just some PHP script you want to ensure doesn’t exceed a certain time limit, while exiting the script safely? Simply use the following function in your script. This is an example of an entire working script. Ordinarily, this script would run for 30 seconds, but thanks to this function, it will exit after 3 seconds.

<?php

$starttime = time();
$runtime = "3"; // How long script should run (in seconds)

for($x=1; $x <= 30; $x++)
    {
    sleep(1);
    echo "Second $x of script has passed!<br>";
    $breaktimer = breaktimer($starttime, $runtime);
    if($breaktimer == "1") { echo "The script has been running for $runtime seconds. Time to stop the script!"; break; }
    }

function breaktimer($starttime, $runtime)
    {
    $breaktimer = "0";
    $now = time()-$starttime; // Calculate how many seconds script has been running for until now
    if ($now >= $runtime) // Return 1 if script has run for allotted run time
        {
        $breaktimer = "1";
        }
    return $breaktimer;
    }

?>

Enjoy!