0

I'm looking for some help with this cURL problem I have.

I'm experiencing slow response when I'm using the cURL function below. I have a list of about 40 ids that I pass to the function in a for loop - the URL does not change. Once I get the reponse from each id, I store the data I need in a JSON array (to iterate through the JSON array I have another for loop within the id for loop) and echo the result. I am 99% certain I've isolated the issue to cURL as I can see the response requests taking a long time in Chrome Development Tools.

I'm thinking there has to be a better way to do this because it's taking a really long time to complete, getting up to 10 minutes. When I test the requests via Postman or my browser the response is almost instant. I can manually complete getting the resposnes quicker than I can with PHP/cURL.

So, I'm thinking there has to be a better way to do this but I just can't seem to work it out.

public function cURLfunction($url, $id){

        //example $url = "https://mywebsite.com/getIdData/";
        //example $id = "100569841";
        
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url . "/" . $id);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        
        $result = curl_exec($curl);
        
        curl_close ($curl);
        
        return $result;
 
}//end cURLfunction 

Any help is greatly appreciated

Kahlil

Kahlil N
  • 71
  • 2
  • 10
  • 2
    For starters, don't run **curl_init** and all the setup every time; create your **$curl** object and options outside the loop, and just set the URL and call **curl_exec** inside the loop. – Don R Apr 27 '21 at 17:12
  • Also, do you control `https://mywebsite.com/getIdData/` and if so, can you just make it accept multiple IDs? – Chris Haas Apr 27 '21 at 17:58
  • @DonR Thanks! Will give this a go and see what the improvement is like – Kahlil N Apr 27 '21 at 22:15
  • @ChrisHaas I don't have control of mywebsite - I'm using their API – Kahlil N Apr 27 '21 at 22:16
  • Thanks @DonR - I applied your suggestion and it has improved the response time by a few seconds, it wasn't dramatic enough to notice a big difference. What else could cause the sluggish response? Thanks agian – Kahlil N Apr 28 '21 at 10:39
  • Here's a [post with some suggestions](https://stackoverflow.com/q/19467449/231316), I specifically like the DNS recommendations. – Chris Haas Apr 28 '21 at 13:32

0 Answers0