Passing arrays of urls in Curl request

2993 views php
5

I need to pass multiple url parameters to make a single CURL request. Not sure but whenever I use foreach loop it make calls only on the last url.

Here is my code

$urls = array(
  'https://example.com?id=346428437&league_id=35',
  'https://example.com?id=346428437&league_id=36',
  'https://example.com?id=346428437&league_id=37',
  'https://example.com?id=346428437&league_id=38',
  'https://example.com?id=346428437&league_id=39',
  'https://example.com?id=346428437&league_id=40'
);
foreach($urls as $uri){
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$data = curl_exec($ch) or die(curl_error($ch));
if ($data === false) {
    $info = curl_getinfo($ch);
    curl_close($ch);
    die('error occured during curl exec. Additioanl info: ' . var_export($info));
 }
curl_close($ch);
}

It appears to call only the last url.

answered question

"It appears" - how do you test that? ($data will be overwritten in each call, so you'll only see the last result)

"https://example.com&league_id=..." is wrong syntax btw. should be "https://example.com?league_id=..."

@Jeff When i dump the data it prints the results of last url param.

now re-read my first comment.

Yes i know that. I forgot to put this in the post

1 Answer

5

in your case die function stop execution if CURL unable to process url

try this

$urls = array(
  'https://example.com&league_id=35',
  'https://example.com&league_id=36',
  'https://example.com&league_id=37',
  'https://example.com&league_id=38',
  'https://example.com&league_id=39',
  'https://example.com&league_id=40'
);
foreach($urls as $uri){
  $ch = curl_init($uri);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

  $data = curl_exec($ch);
  if ($data === false) {
      $info = curl_getinfo($ch);
      echo 'error occured during curl exec. Additioanl info: ' . var_export($info);
   }
  curl_close($ch);

}

posted this

Have an answer?

JD

Please login first before posting an answer.