file_get_contents retry on error and slow down

I am using file_get_contents to get the contents of many files on a remote server. Occasionally I get a "failed to open stream: HTTP request failed! HTTP/1.1 503 Service Unavailable" error. I would like to write my PHP code to just retry N times when this happens until there is success. I am also worried that my PHP script may be calling up this files too quickly, is there a way to slow down a for loop?

foreach ($links as $page) {
  $contents = file_get_contents($page);
  $descriptions[$i] = strip_tags($contents);

$links is an array of about 2500 pages.
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Richard DavisSenior Web DeveloperCommented:

as for slowing your loop down you can use the sleep function to delay execution by x number of seconds

foreach ($links as $page) {
  $contents = file_get_contents($page);
  $descriptions[$i] = strip_tags($contents);
  sleep(3); // wait 3 seconds before continuing interations

the only drawback to this is that (untested opinion here) it may cause your php server to have an execution timeout error if the loop takes longer than the ini file's setting for max code execution time.

As for your set amount of retries, I would think you could count the number of false values returned by file_get_contents and when it matches the preset, to exit or skip that implementation of the call. If file_get_contents can't read a file, it will return false.

Simply create a var called $ct and initialze it to zero. then each time file_get_contents returns a false, do a $ct++ and test it agains a preset retry value of say '3' or something you choose.

Hope this helped :)

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sypderAuthor Commented:
That does help. Thanks.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.