PHP run loop and script at same time

2019-08-29 16:52发布

问题:

I'm currently running a loop in my PHP script to check if the user connection has been aborted (connection_aborted() does not work on ajax calls):

connection_check.php:

<?php
ignore_user_abort(true);
for ($i = 0; $i < 1000; $i++) {
    echo "<br>";
    flush();
    ob_flush();
    if (connection_aborted()) {
        echo "nocon";
        exit;
    } else {
        // Everything is fine
    }
    sleep(3);
}
?>

However, I also need to run the rest of my PHP code while this loop is running in the "background" so that when the connection is aborted, the script dies, but if it is not, the script should continue to run. I need to do this because I'm calling this PHP file with an ajax call.

This is what I've tried, however, it isn't working (the script continues to run and does not die, connection_check.php does not echo "nocon"):

file.php

<?php
$child = fopen('http://ipaddress/core/connection_check.php', 'r');

/***
* ALL PHP CODE HERE THAT SHOULD START RUNNING RIGHT AWAY WHILE CONNECTION_CHECK.PHP RUNS IN THE BACKGROUND
***/

$response = stream_get_contents($child);

if($response == "nocon") {
    die();
}
?>

Any help? If anybody has an alternative, that would be appreciated as well. I've been tring to work on this for over a day, and no luck yet.

回答1:

In your code you are calling sleep(3) within your loop and your loop is running 1000 times, have you tried waiting 3000 seconds for the loop to finish? I assume you are wanting to check every 3 seconds that the user is still connected.

My suggestion would be to remove the sleep, remove the loop and make your PHP essentially check the connection only once and return a relevant response. Call this PHP via AJAX, every X seconds. You can look at setTimeout and setInterval in Javascript to achieve this. Perhaps set a timeout every time the AJAX call is completed to call it again.

Something like this (Javascript/jQuery)

function checkConnection() {
    // Ajax call here
    $.ajax({
        // Other AJAX stuff
        complete: function() {
           setTimeout(function(){
               checkConnection();
           }, /*<YOURTIMEHERE>*/);
        }
    });
}

checkConnection();

Or even better you could put the setTimeout bit inside your success callback when the connection is considered active.



回答2:

use:

ob_start(); then your loop