0

I am trying to code a crawler based on PHP with curl. I have database of 20,000-30,000 URLs that I have to crawl. Each call to curl to fetch a webpage takes around 4-5 seconds.

How can I optimize this and reduce the time required to fetch a page?

Gowtham
  • 386
  • 5
  • 20
  • related SO question -> http://stackoverflow.com/questions/13139704/multi-thread-multi-curl-crawler-in-php – Gowtham Dec 06 '12 at 07:19

1 Answers1

1

You can use curl_multi_* for that. The amount of curl resources you append to one multi handle is the amount of parallel requests it will do. I usually start with 20-30 threads, depending on the size of returned content (make sure your script won't terminate on memory limit).

Note, that it will run as long as it takes to run the slowest request. So if a request times out, you might wait for very long. To avoid that, it can be a good idea to set timeout to some acceptable value.

You can see the code example at my answer in another thread here.

Community
  • 1
  • 1
Ranty
  • 3,333
  • 3
  • 22
  • 24
  • in your code, which loop does all the downloading? The while loop with curl_multi_exec or the for loop with curl_multi_getcontent? – Gowtham Dec 06 '12 at 12:36
  • Do you mean *when do I get the content of the pages I request?* If that, then `$content = curl_multi_getcontent` is what you want. `$content` here is analog of `$content = curl_exec($ch);`. – Ranty Dec 06 '12 at 13:54
  • I mean when the download is actually happening. I can process all the pages later sequentially. I don't need the processing to be multi threaded. Just the downloading part is sufficient. If curl_multi_getcontent is equivalent to curl_exec, I can't see where the parallel downloading is happening since I am just downloading pages in a loop, which I feel can be done with single threaded curl also. What am I missing here? – Gowtham Dec 06 '12 at 18:57
  • 1
    The download itself is happening in a middle loop where the line `curl_multi_exec($cmh, $running);` is. With `curl_multi_getcontent` you just get the content of the downloaded page. About `curl_exec` I meant that it returns the content. I didn't mean it executes at that point. – Ranty Dec 06 '12 at 21:27