[PHP] Server Check and Failover Code

Here is some sample PHP code you can run if you have a PHP web application that uses code or images from an ad server, image server, or content deliver network, and you want to check if it is working and if not, failover to another one:

<?php

$current_server = "server.domain.com";

// set frequency based on your server traffic
$freq = 100;

if(rand(1,$freq) == 1){

        // create curl resource
        $ch = curl_init();

        // set url
        curl_setopt($ch, CURLOPT_URL, "server.domain.com/heartbeat.html");

        // don't get header
        curl_setopt($ch, CURLOPT_HEADER, 0);

        // 2 second connection timeout
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);

        // store results as the return of curl_exec
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

        // 2 second curl timeout
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);

        // if HTML error 400 over over, fail
        curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);

        $subject = curl_exec($ch);
        $pattern = '/YOUR_PATTERN_HERE/';
        $errno = preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
        if($errno == 0) $current_server  = "backup.domain.com";
        curl_close($ch);
}
?> 

I chose a random number to sample the server but you could change the code and put a timer or counter if you like that better..