Mr.Smithyyy
Mr.Smithyyy

Reputation: 1339

Run multiple curl calls consecutively with same options

I have a curl call I want to run but once it runs, I would like to run another to a different url but with the same options.

Can I run another call without having to copy and paste the options, I need to run about 5 calls, it seems like there is a way to accomplish this. I cannot run them all at the same time, I need to make sure that I get the result from one, then if certain critera is met, I need to run another one.

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);

$result = curl_exec($ch);

curl_close($ch);

Upvotes: 1

Views: 4063

Answers (2)

protld
protld

Reputation: 440

If I haven't understood wrongly.

Yes, I always use a way to run 1 cURL action to more than 1 URL.

And you should use:

EDIT: Method 2 isn't working.

Method 1:

<?php
// Arrays
$ch=array();
$url=array();
$result=array();
// ************

$url['1'] = 'http://url1.com';
$url['2'] = 'http://url2.com';

$ch['1'] = curl_init($url['1']);
curl_setopt($ch['1'], CURLOPT_HEADER, true);
curl_setopt($ch['1'], CURLOPT_NOBODY, true);
curl_setopt($ch['1'], CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch['1'], CURLOPT_TIMEOUT, 10);

$result['1'] = curl_exec($ch['1']);

curl_close($ch['1']);

$ch['2'] = curl_init($url['2']);
curl_setopt($ch['2'], CURLOPT_HEADER, true);
curl_setopt($ch['2'], CURLOPT_NOBODY, true);
curl_setopt($ch['2'], CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch['2'], CURLOPT_TIMEOUT, 10);
$result['2'] = curl_exec($ch['2']);
curl_close($ch['2'])
?>

Method 2

<?php
$url = array(
'http://url1.com',
'http://url2.com'
);
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);

$result = curl_exec($ch);

curl_close($ch)
?>

In method 1 we used arrays in $ch and $url and $result

In method 2 we made array of $url

Upvotes: 0

Patrick Q
Patrick Q

Reputation: 6393

Simply update the url (using the CURLOPT_URL option) before each additional request. See the comments in the below example.

// initialize with the first url you want to use
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);

$result = curl_exec($ch);

// check the result of the first request
if($result == "the content you want")
{
    // if the result dictates that you make another request, update the url
    curl_setopt($ch, CURLOPT_URL, $url2);

    // execute the second request
    $result2 = curl_exec($ch);

    // do something with $result2
}

// only close curl after you are done making your requests
curl_close($ch);

Upvotes: 3

Related Questions