如何在50秒后运行PHP脚本的一部分?

如何在50秒后运行PHP脚本的一部分?,php,loops,curl,time,while-loop,Php,Loops,Curl,Time,While Loop,我有一个脚本,它使用curl从web服务获取响应。curl返回的响应是用于检查注册状态的url。响应是JSON格式的,因此需要首先对其进行解码。解码后,通过获取url的内容来检查状态。从内容中检索并显示注册状态,以让用户知道。注册可能需要50秒,因此我需要在50秒后再次检查状态。sleep或usleep不适用于此,因此我要做的是获取当前时间,暂停/等待50秒,然后再次检查状态。我想用while循环来做这个,但是我在做这个时遇到了一个问题。代码如下: <?php function sendR

我有一个脚本,它使用curl从web服务获取响应。curl返回的响应是用于检查注册状态的url。响应是JSON格式的,因此需要首先对其进行解码。解码后,通过获取url的内容来检查状态。从内容中检索并显示注册状态,以让用户知道。注册可能需要50秒,因此我需要在50秒后再次检查状态。sleep或usleep不适用于此,因此我要做的是获取当前时间,暂停/等待50秒,然后再次检查状态。我想用while循环来做这个,但是我在做这个时遇到了一个问题。代码如下:

<?php
function sendRequest($url, $params)
{
    $request = curl_init($url); // initiate curl object
    curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
    curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
    curl_setopt($request, CURLOPT_POSTFIELDS, $params); // use HTTP POST to send form data
    curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response.
    $response = curl_exec($request); // execute curl post and store results in $post_response
    curl_close ($request); // close curl object
    return $response;
}

function sendJSONRequest($url, $data)
{             
    $data_string = json_encode($data);
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);               
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);             
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);     
    curl_setopt($ch, CURLOPT_TIMEOUT ,50);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                       
        'Content-Type: application/json',
        'Accept: application/json',
        'X-MP-Version: 10072013')                      
    );
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    ob_start();
    $result = curl_exec($ch);
    $info = curl_getinfo($ch);
    if ($result === false || $info['http_code'] == 400) {
      return "0";
    } else {
      return $result;
    }
    ob_end_clean();
    curl_close($ch);
}

function WriteLog($offer,$values)
{
    $Filename = "./reports/".$offer.date('Ym').".txt";
    $fh = fopen($Filename, 'a') or die("can't open file");
    $filecontent = date('Y-m-d G:i').',';
    $filecontent .= $values;
    $filecontent .= PHP_EOL;
    fwrite($fh,$filecontent);
    fclose($fh);
}

// Get Variables sent from websites
$uname = $_GET['un'];
$usname = $_GET['ul'];
$uphone = $_GET['up'];
$uemail = $_GET['ue'];
$testlive = $_GET['test'];
$aff_id = $_GET['aff'];
$unique_id = $_GET['uid'];
$password = md5($_GET['pass']);
$mnumber = $_GET['meter'];
$bank = $_GET['bank'];
$camp = $_GET['camp'];
// Convert URL and Name split
$rurl = 'http://'.$_GET['rurl'];

// Split Name if no surname entered
if (strlen($usname) > 0) {
    $firstname = $uname;
    $lastname = $usname; // I have a first and lastname
} else {
    list($firstname, $lastname) = explode(" ",$uname,2); // I only entered my firstname
}
// Determine phone number format
$phoneformat = strpos($uphone,'-');
if($phoneformat === false) {
 // string - NOT found in haystack
 $phonesubmit = $uphone; 
} else {
    $phone1 = substr($uphone,0,3);
    $phone2 = substr($uphone,4,3);
    $phone3 = substr($uphone,8,4);
    $phonesubmit = $phone1.$phone2.$phone3;
}
// Determine Live or Test
$testlive = strtolower($testlive);
switch ($testlive) {
    case "test":
        $debug=true; //Set this to 'false' to redirect users
        $mpurl = 'http://stageapi.myprepaid.co.za/api/ConsumerRegisterRequest'; // Set to TEST environment
        break;
    case "live":
        $mpurl = 'https://api.myprepaid.co.za/api/ConsumerRegisterRequest'; // Set to LIVE environment
        break;
}

// Set Variables
$data = array("Email" => "$uemail", "Mobile" => "$phonesubmit", "Password" => "$password", "MeterNumber" => "$mnumber", "Bank" => "$bank", "CampaignID" => "$camp");

$response = sendJSONRequest($mpurl, $data);
if($debug) echo "Response: ".$response."<br />";

// If Customer Exists
if ($response == "0"){
    header ("location: https://www.myprepaid.co.za?affid=1040");
} else {

    $res = json_decode(file_get_contents($response), true);

    if($debug) echo "<pre>";
    if($debug) "\n" .print_r($res). "\n";
    $now = time();

    //Read values from response
    $rid = $res["ID"];
    $stat = $res["Status"];

    // Post to Trax

    $traxurl = "http://trax1.internetmarketingupstart.com/SP3o?"; //Trax URL
    $trax_post_string = 'aff_id='.$aff_id.'&aff_sub='.$unique_id;
    $trax_post_string .= '&aff_sub2='.urlencode($uname).'+'.urlencode($usname);
    $trax_post_string .= '&aff_sub3='.urlencode($uphone);
    $trax_post_string .= '&aff_sub4='.urlencode($uemail);
    $trax_post_string .= '&aff_sub5=';
    $trax = sendRequest($traxurl, $trax_post_string);

    if($debug) echo("\nTrax Result: {$trax} \n");

    // LOG ALL POSTS
    $logdetail = $aff_id.','.$unique_id.','.$testlive.','.$firstname.','.$lastname.','.$phonesubmit.','.$uemail.','.$rid.','.$stat.','.$trax;
    WriteLog("mypepaid",$logdetail);

    // ALL DONE -REDIRECT
    // Determine if ReturnURL contains variables
    $pos = strpos($rurl,'?');
    if($pos === false) {
     $urlconnector = '?';
    } else {
      $urlconnector = '&';
    }

    // Redirect to Confirmation page provided
    $URL=$rurl.$urlconnector.'un='.urlencode($firstname).'&ul='.urlencode($lastname).'&up='.urlencode($phonesubmit).'&ue='.urlencode($uemail).'&status='.urlencode($stat);
    if($debug) echo("Redirect to Confirmation URL:\n{$URL}");
    if(!$debug) header("Location: {$URL}");

    //Recheck the registration status after 50 seconds.
    while(time() <= $now + 50):
        if ($now == ($now + 50)):
            $result = json_decode(file_get_contents($response), true);
            $lateststat = $result["Status"];

            $NewURL=$rurl.$urlconnector.'un='.urlencode($firstname).'&ul='.urlencode($lastname).'&up='.urlencode($phonesubmit).'&ue='.urlencode($uemail).'&status='.urlencode($lateststat);
            echo "<script>javascript:window.location = '".$NewURL."';</script>";
        endif;
    endwhile;
}
?>

您可以通过jQuery使用AJAX并调用php函数来检查流程是否完成。您可以通过设置一个时间间隔来实现这一点,这样jQuery会每隔x秒检查一次,直到您得到所需的响应。他说如果可能的话,我会使用PHP,但似乎有些事情单靠PHP是做不到的,这就是为什么我在代码的最后一部分加入了javascript。如果不使用AJAX,你必须告诉JS在指定的时间间隔刷新页面,直到你发送的PHP变量正确为止。由于PHP仅在每次请求页面时发送数据(如果页面更新),因此必须刷新页面,以便JS可以访问数据。这就是AJAX很有用的地方,因为您可以在不刷新页面的情况下执行相同的操作。为什么睡眠不适用?我不明白您的意思……睡眠会延迟您放置它的代码。