4

I have many HTTPS-URLS where I have to find a Special Phrase, so I´m trying to use cURL in a foreach Loop, but it´s not working.

...
foreach($sites as $site) {

    $URL = $site;        

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

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

}

print substr($response, $start, $i);
...

If I use just a single HTTPS-URL I get the Phrase, but inside a foreach-loop it´s not working. Can someone help me? (:

Please excuse my poor english..

2
  • Is there some warning/error? If not, maybe they're turned off from the php.ini file that is used. Make sure they're turned on and check for any notices/warnings/errors. Commented Dec 3, 2017 at 21:26
  • For people with a bit like my case. In my case, I have placed the curl code with a return statement in a function and called that function in foreach loop. So when the first call was done, the return statement was executed and the loop was stopped. I have put the return statement in a if condition for specific calls, and it worked fine. Commented Nov 6, 2020 at 10:38

1 Answer 1

5

this may help :) store result inside an array

$sites = ['https://stackoverflow.com','http://example.org'];
$result = [];
foreach ($sites as $site) {

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $site);

    // User agent
    curl_setopt($ch, CURLOPT_USERAGENT, "PHP Curl");

    // Include header in result? (0 = yes, 1 = no)
    curl_setopt($ch, CURLOPT_HEADER, 0);

    // Should cURL return or print out the data? (true = return, false = print)
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    // execute the given URL, and return output
    $result[] = curl_exec($ch);

    curl_close($ch);


}

var_dump($result);
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah ! Thank you <3
Hi. What if I have like 10000 reigsters on the $sites array, and the function times out after 60 seconds? How can I make sure all the cURL requests were sent?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.