Search code examples
phpcachingfile-get-contentsfault-tolerance

Fault-tolerant file_get_contents


I have a website with the following architecture:

End user     --->    Server A (PHP)        --->        Server B (ASP.NET & Database)
             web                    file_get_contents
           browser                  

Server A is a simple web server, mostly serving static HTML pages. However, some content is dynamic, and this content is fetched from Server B. Example:

someDynamicPageOnServerA.php:
<html>
     ...static stuff...

     <?php echo file_get_contents("http://serverB/somePage.aspx?someParameter"); ?>

     ...more static stuff...
</html>

This works fine. However, if server B is down (maintainance, unexpected crash, etc.), those dynamic pages on server A will fail. Thus, I'd like to

  • cache the last result of file_get_contents and
  • show this result if file_get_contents timeouted.

Now, it shouldn't be too hard to implement something like this; however, this seems to be a common scenario and I'd like to avoid re-inventing the wheel. Is there some PHP library or built-in feature that helps which such a scenario?


Solution

  • i would do something like this:

    function GetServerStatus($site, $port){
        $fp = @fsockopen($site, $port, $errno, $errstr, 2);
        if (!$fp) {
           return false;
        } else { 
           return true;
        }
    }
    
    $tempfile = '/some/temp/file/path.txt';
    
    if(GetServerStatus('ServerB',80)){
         $content = file_get_contents("http://serverB/somePage.aspx?someParameter");
         file_put_contents($tempfile,$content);
         echo $content;
    }else{
         echo file_get_contents($tempfile);
    }