'PHP AJAX echo json data before then sleep

I have tried out couple answers here but none worked.

I have this basic honeypot script:

  if (!empty($_POST['starttime'])) {

        $current_time = time();
        $json = array();
        $json = reGenerateFormFields();//hold the hashed keys arays for change in the key output.

        if (($current_time - htmlentities(@$_POST['starttime'])) < 4) { // 3 is number of seconds differential
                        $return = array('hp' => true,'message' =>'אנא המתן 3 שניות בין שליחה','key' => $json['2'], 'nonce' => $json['1'],'time' => time());
              echo json_encode($return);
            sleep(7);
            die();
            
        }
}

I am trying to echo the json message and then sleep. But now it is first do sleep then echo the message. Any idea how to do it the good way?



Solution 1:[1]

Most likely the echo'd data is just being buffered rather than sent until sleep finishes and the request completes. Try using flush() to force pushing the output to the client:

echo json_encode($return);
flush();
sleep(7);
die();

If this fails, you may find padding the output will help meet the server/browser's minimum length requirement to flush/display the data:

echo str_pad(json_encode($return),8192," ");
flush();
sleep(7);
die();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1