I'm new to php and I want to control a php while loop script, using buttons (start/stop), the start button make an ajax call to the start.php script that define $_SESSION['loop'] = TRUE and execute the loop, the stop button make an ajax call to the stop.php script that just change $_SESSION['loop'] to FALSE.
Below is my code so far, but when I hit the stop button I became the alert (success stop) only after the while loop finish looping, which mean the loop didn't break as I was assuming.
I think it's something with the session that is locked while the loop is executing. If so, how to change the $_SESSION['loop'] value and make the loop read that value each time?
index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#start').click(function(){
$.ajax({
url: "start.php"
});
});
$('#stop').click(function(){
$.ajax({
url: "stop.php",
success: function(){
alert('success stop');
},
error: function(){
alert('failure stop');
}
});
});
});
</script>
<button id="start">Start</button>
<button id="stop">Stop</button>
start.php
<?php
session_start();
$_SESSION['loop'] = TRUE;
ini_set('max_execution_time', 300);
$i = 0;
while($i < 100) {
if ($_SESSION['loop'] == TRUE) {
//query to save some variables
// Pause 10s after saving 2
if ($i != 0 && $i%2 == 0) {
sleep(10);
}
$i++;
} else {
break;
}
}
?>
stop.php
<?php
session_start();
if(isset($_SESSION['loop'])) {
$_SESSION['loop'] = FALSE;
}
?>
if($_SESSION['loop']..should be a sql select query and$_SESSION['loop']=..should be an sql update query