PHP long running script without Ajax

<?php
header("Content-Type:text/html;charset=utf-8");
session_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type"  content="text/html; charset=utf-8" />
</head>
<body>
<?php

$executiontime = 5; // max time for scripting
$sleeptime = 3; // seconds to pauze after execution time limit


if(!isset($_GET["continue"])){

	$_SESSION["numbers"] = range(1,100000);
	$_SESSION["genesis"] = microtime(true); // absolute start time
	echo count($_SESSION["numbers"]);

}

$_SESSION["starttime"] = microtime(true); // 'this round' start time

foreach($_SESSION["numbers"] as $key=>$value){

		sleep(1);
		// abort and 'reload' upon exceeding execution time
		if((microtime(true) - $_SESSION["starttime"]) > $executiontime){
			echo "<p>" . count($_SESSION["numbers"]) . " items left";			
			echo "<br>This round: " . round((microtime(true) - $_SESSION["starttime"]),2) . " seconds";		
			echo "<br>Total time: " . round((microtime(true) - $_SESSION["genesis"])/60,2) . " minutes";
			echo "<p><strong>Pause script...</strong> Resume in $sleeptime seconds...</p>";
			die ('<meta http-equiv="refresh" content="'.$sleeptime.';URL='.$_SERVER['SCRIPT_URI'].'?continue=1" /></body></html>');
		}
		
		// do some stuff while execution time is still ok
	
		unset($_SESSION["numbers"][$key]);
}

echo "<br>Completed...: total time " . round((microtime(true) - $_SESSION["genesis"])/60,2) . " minutes";

Leave a Reply

Your email address will not be published. Required fields are marked *