简体   繁体   中英

How can I iteratively send a post request, in a loop, to a remote server with PHP?

I am trying to send data to a server a number of times, depending on the size of an array. The loop correctly sends data one time but does not thereafter. My code is:

    $id = "uuid" //dynamic  
    $username = "emailadd@example.com";
    $password = "password";
    $serverurl = "http://0.0.0.0:8080/api/v1/experiments/". $id ."/buckets";

    $alloc = floor((1 / sizeof($arrayAsBigAsValueArray)) * 100) / 100;
    $sum = 0;
    for ($x = 0; $x < sizeof($valuearray); $x++){

        $datasobj = array(
            "label" => $arrayAsBigAsValueArray[$x], 
            "allocationPercent" => $alloc,
            "payload" => json_encode(array('mykey'=>$valuearray[$x]),JSON_UNESCAPED_SLASHES)
        );

        if($x< sizeof($valuearray)-1){
            $sum += $alloc;
        }
        else{
            if((1 - $sum) != 0){
                $datasobj ["allocationPercent"] = (1 - $sum); 
            }
        }

        $headers = array(
            "Content-type: application/json",
            "Authorization: Basic " . base64_encode("$username:$password")
        );

        $ch = curl_init($serverurl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $datasobj);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $result2 = curl_exec($ch);
        curl_close($ch);
    }

This function is called from WordPress' admin-ajax, and a javascript function calls it. I get a 400 error when X > 0. How can I fix this? I am trying to use the Wasabi A/B api, which can be found here .

Where is the 400 coming from? Your server or Wasabi?

If its from Wasabi, on your curl request, I suspect a rate limiter on the API. You will have to put a delay between request. Simplest is sleep().

Or,

"payload" => json_encode(array('mykey'=>$valuearray[$x])...

Is there multiple Authorization key, one for each request? Is the array filled properly?

Check the 400 errors: https://wasabi.com/wp-content/themes/wasabi/docs/API_Guide/topics/Error_Responses.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM