简体   繁体   中英

For loop with Curl request - PHP

I'm checking against a list of address books (outputted as checkboxes) to see which books the user has selected. For the selected ones I'm adding them to an ESP via their API using curl.

I have the following code which is achieving the desired result, however it's causing a pretty slow page load, I think this is because I'm looping through a large chunk of curl requests up to 15 times (once for each address book) and wondered if someone could help me tidy this up?

$aBook = $_POST['addressBooks'];
$N = count($aBook);

    for($i=0; $i < $N; $i++)
    {
      $content = [
            'email' => $_POST['email']
        ];
        global $baseUrl, $apiUsername, $apiPassword;
        $url = $baseUrl . '/v2/address-books/' . $aBook[$i] . '/contacts';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt(
            $ch, CURLOPT_HTTPHEADER, array('Accept: application/json',
                                           'Content-Type: application/json')
        );
        curl_setopt($ch, CURLAUTH_BASIC, CURLAUTH_DIGEST);
        curl_setopt(
            $ch, CURLOPT_USERPWD,
            $apiUsername . ':' . $apiPassword
        );
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($content));

        $response = json_decode(curl_exec($ch));

    }

Since $abook is an array, why not serialize it and send just one curl request and do your backend processing once. If firing multiple queries using transactions would be good.

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