Code

Coding, Programming & Algorithms, Tips, Tweaks & Hacks
Search

get_file_contents

Sometimes we need to retrieve a remote file/url's content which is easily done using PHP's file_get_contents(). This returns FALSE on failure but on many occasions file_get_contents() returns FALSE due to a network error or server overload and could've worked the next second. Here is a function get_file_contents(), that tries to retrieve the url's contents over and over again until its TRUE (it has successfully fetched the contents) or until it has exhausted the number of tries. Because threading is not yet available in PHP, it is not recommended to set the $totalTries to a higher value.
PHP
function get_file_contents($url, $totalTries = 5)
 {
        $Tries = 0;
        do
         {
                if ($Tries > 0) sleep(1); # Wait for a sec before retrieving again
                $contents = @file_get_contents($url);
                $Tries++;
         } while ($Tries <= $totalTries && $contents === FALSE);
         if ($contents == "") $contents = FALSE;
         return $contents;
 }
This ends the beginning of my first post here !
Vanakkam !

0 comments: