Skip to content

Instantly share code, notes, and snippets.

@shinnn
Last active October 8, 2015 07:38
Show Gist options
  • Save shinnn/3300657 to your computer and use it in GitHub Desktop.
Save shinnn/3300657 to your computer and use it in GitHub Desktop.
Loading CDN-hosted jQuery with triple fallbacks in PHP
<?php
// ref: http://www.php.net/manual/ja/function.file-exists.php#79118
function getResource(){
$args_last_key = func_num_args() - 1;
$resource_urls = array_slice(func_get_args(), 0, $args_last_key);
// The last argument is a local file path.
$local_fallback = func_get_arg($args_last_key);
foreach($resource_urls as $url){
//参考 http://www.php.net/manual/ja/function.file-exists.php#79118
$handle = curl_init($url);
if(false === $handle){
continue;
}
curl_setopt($handle, CURLOPT_HEADER, false);
curl_setopt($handle, CURLOPT_FAILONERROR, true); // this works
curl_setopt(
$handle,
CURLOPT_HTTPHEADER,
array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15")
); // request as if Firefox
curl_setopt($handle, CURLOPT_NOBODY, true);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
$connectable = curl_exec($handle);
curl_close($handle);
if($connectable){
return print str_replace(array("http:", "https:"), "", $url);
}
}
echo $local_fallback;
return false;
}
?>
<?
define('JQ_VER', '1.9.1');
echo "<script src=\"";
getResource(
"https://ajax.googleapis.com/ajax/libs/jquery/".JQ_VER."/jquery.min.js",
"http://code.jquery.com/jquery-".JQ_VER.".min.js",
"http://ajax.aspnetcdn.com/ajax/jQuery/jquery-".JQ_VER.".min.js",
"js/jquery.js"
);
echo "\"></script>\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment