如何在PHP中的两个回显之间增加延迟?

时间:2019-05-03 18:32:47

标签: php

我正在尝试在每次回声之间添加5秒的延迟,以使用户能够看到状态。

我的代码

add_action( 'gform_pre_submission_8', 'pre_submission_handlerr' );

function pre_submission_handlerr( $form ) {

$current_user = wp_get_current_user();
global $wpdb; 


$checkip = $_POST['input_8'];

echo "IP Requested: . $checkip";

$result = $wpdb->get_var("SELECT EXISTS(SELECT * from wp_gf_entry_meta WHERE meta_value like '$checkip');"); 

  if ( $result == 1) {
  $_POST['input_7'] = 'Approved';
  sleep(5);
  echo "Status: Found";
  sleep(5);

 }

if ( $result == 0) {
$_POST['input_7'] = 'Not Approved';
echo "Status: Not Found";
}
   }

但是,我看到延迟实际上是在开始处,并且我希望延迟在两个回波之间没有延迟

WordPress中的PHP代码段(重力形式)

任何反馈将不胜感激

谢谢! 娜塔莉(Nathalie)

1 个答案:

答案 0 :(得分:0)

这样做可能不是最好的主意。您可能还有其他方法可以使脚本异步,我猜想在客户端使用Promises

但是,这可能会帮助您做到这一点:

add_action('gform_pre_submission_8', 'pre_submission_handlerr');

function preSubmissionHandlerr($form)
{
    $current_user = wp_get_current_user();
    global $wpdb;
    $checkip = $_POST['input_8'];
    echo "IP Requested: . $checkip";

    $result = $wpdb->get_var("SELECT EXISTS(SELECT * from wp_gf_entry_meta WHERE meta_value like '$checkip');");

    if ($result == 1) {
        $_POST['input_7'] = 'Approved';
        flush();
        sleep(5);
        flush();
        echo "Status: Found";
        flush();
        sleep(5);

    }

    if ($result == 0) {
        $_POST['input_7'] = 'Not Approved';
        echo "Status: Not Found";
    }
}

或者,如果您愿意,也可以使用ob_implicit_flush();,它可能也可以工作一次或多次:

add_action('gform_pre_submission_8', 'pre_submission_handlerr');

function preSubmissionHandlerr($form)
{
    $current_user = wp_get_current_user();
    global $wpdb;
    $checkip = $_POST['input_8'];
    echo "IP Requested: . $checkip";

    $result = $wpdb->get_var("SELECT EXISTS(SELECT * from wp_gf_entry_meta WHERE meta_value like '$checkip');");

    if ($result == 1) {
        ob_implicit_flush(true);
        $_POST['input_7'] = 'Approved';
        sleep(5);
        ob_implicit_flush(false);

        ob_implicit_flush(true);
        echo "Status: Found";
        sleep(5);
        ob_implicit_flush(false);

    }

    if ($result == 0) {
        $_POST['input_7'] = 'Not Approved';
        echo "Status: Not Found";
    }
}