• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 712
  • Last Modified:

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);
  $i++;
}

$links is an array of about 2500 pages.
0
sypder
Asked:
sypder
1 Solution
 
Richard DavisSenior Web DeveloperCommented:
hello,

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);
  $i++;
  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 :)
0
 
sypderAuthor Commented:
That does help. Thanks.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now