I need some help. I would like to create a fallback for my source code. I am using a cdn to host my javascript and css and images. What I am trying to do is create a fallback in php that will say for instance is ip 123.456.789 is not available in 400ms the php will fallback to fetch my local storage at 987.654.321
I was thinking something on the lines of this:
if ip 123.456.789 in 400ms
//show this file from 123.456.789
else
//show this file from 987.654.321
I have my source code hard coded such as:
<script type="text/javascript" src="123.456.789/js/jquery.js"></script>
So if 123.456.789 is not available in 400ms I would like this one to load
<script type="text/javascript" src="987.654.321/js/jquery.js"></script>
I answered my own question a while ago. So decided to share here.
<?php
//debug off by default
error_reporting(0);
//cdn fallback
if (!isset($_GET['aws_cdn'])) {
$cdn_fallback = curl_init('http://123.456.789/'); //Set to CDN IP or URL
curl_setopt($cdn_fallback, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cdn_fallback, CURLOPT_NOSIGNAL, 1);
curl_setopt($cdn_fallback, CURLOPT_TIMEOUT_MS, 400); //How many milliseconds before fallback to local storage
$data = curl_exec($cdn_fallback);
$curl_errno = curl_errno($cdn_fallback);
$curl_error = curl_error($cdn_fallback);
curl_close($cdn_fallback);
if ($curl_errno > 0) { ?>
<script type="text/javascript" src="http://example.com/js/jquery.js"></script>
<?php } else { ?>
<script type="text/javascript" src="http://123.456.789/cdn/js/jquery.js"></script>
<?php }} ?>