I have a LAMP server on a Raspberry Pi 4 with a web page that is making an AJAX call to a php script that restarts the pi. My script echo's a JSON string response back to the web page indicating it is preparing to restart then it executes the "sudo reboot" command. The script runs 100% of the time and always restarts but the echo is not always fully transmitted prior to the pi rebooting which causes errors.
Example Code:
<?php
... other code
$tags['status'] = "restarting";
echo json_encode($tags);
$cmd = "sudo reboot";
exec($cmd);
?>
I tried adding a sleep() statement after the echo but that halts the entire script and does not echo until after the sleep. I also tried adding the sleep to the exec command like "sleep 5; sudo reboot" but that does not work either.
If I comment out the reboot statement, I get the echo response 100% of the time. This tells me I have a timing issue. Is there a way to make sure the echo is fully processed prior to issuing the reboot?
I have searched for answers but not finding anything that helps.