Mr.Smithyyy Mr.Smithyyy - 3 months ago 11
PHP Question

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);

Answer

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);
Comments