Jump to content

if file_get_contents failed...loop?


Mike Solstice

Recommended Posts

Ok, I'm having some trouble with file_get_contents failing & am trying to make a loop that will sleep & then retry a maximum of 3 times before giving up & moving to the next item. I tried using a while loop but I'm getting unexpected T_WHILE, which I assume is because it's already in a while loop?

 

I found this:

 

$maxTries = "3";
for ($try=1; $try<=$maxTries; $try++) {

 

but could use some clarification. Will that only trigger if it failes or do I need to include another if statement like

 

$myfile = file_get_contents("http://example.com"); 
if ($myfile === FALSE) {
$maxTries = "3";
for ($try=1; $try<=$maxTries; $try++) {
sleep(3);
$myfile = file_get_contents("http://example.com"); 
}
else {
//continue with script

 

I hope that makes sense...trying to explain it as best I can without having to post my actual source code as I've had it stolen off forums before & now I have a clone to compete with. ;) I'm not great at putting this into words so if I need to clarify, please feel free to ask. I appreciate any & all help given. Thanks!

 

Link to comment
https://forums.phpfreaks.com/topic/233913-if-file_get_contents-failedloop/
Share on other sites

A for loop executes until the condition part of the loop is met. 

 

You can use break to exit the loop immediately, so you could use your for loop, and inside the loop if your function is successful, break out immediately.

So something like this?

 

$myfile = file_get_contents("http://example.com");
$maxTries = "3";
for ($try=1; $try<=$maxTries; $try++) {
if ($myfile === FALSE) {
sleep(3);
$myfile = file_get_contents("http://example.com"); 
}
else {
break;
//close for loop
}
//continue with script & close else
}
//close else

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.