Remotely Download Google AJAX Libraries Using PHP and curl.

<?php

// Modified a bit from: http://davidwalsh.name/download-google-ajax-libraries

error_reporting(E_ALL);

if (! function_exists('curl_init'))
    die('Curl extension is required.');

/**
 * Get the HTTP reponse code from the request.
 *
 * @param unknown $url
 * @return Ambigous <>
 */
function getHttpResponseCode ($url)
{
    $ch = @curl_init($url);

    @curl_setopt($ch, CURLOPT_HEADER, TRUE);
    @curl_setopt($ch, CURLOPT_NOBODY, TRUE);
    @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
    @curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

    $status = array();
    $response = @curl_exec($ch);

    @curl_close($ch);
    preg_match('/HTTP\/.* ([0-9]+) .*/', $response, $status);

    return $status[1];
}

/**
 * Fetch the content of a remote resource.
 *
 * @param string $url
 * @return mixed NULL
 */
function fetchContent ($url)
{
    $responseCode = getHttpResponseCode($url);

    if (getHttpResponseCode($url) != 200) {
        return null;
    }

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // follow redirects?
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

    $response = curl_exec($ch);

    curl_close($ch);

    return $response;
}

/*
 * Usage
 */

// settings
$contentUrl = 'https://developers.google.com/speed/libraries/devguide';
$saveDir = 'js-libs/';

// fetch the web page
$content = fetchContent($contentUrl);

if (is_null($content))
    die("Failed to fetch: $contentUrl");

    // regex js cdn links
$regex = '/\/\/ajax.googleapis.com\/ajax\/libs\/.*.js/isU';

// match?
preg_match_all($regex, $content, $matches);

// make sure there are no repeated files
$js_files = array_unique($matches[0]);

// download every file and save locally
foreach ($js_files as $file) {

    $resourceUrl = 'http:' . $file;

    // download
    $content = fetchContent($resourceUrl);

    if (! is_null($content)) {
        $path = parse_url($resourceUrl, PHP_URL_PATH);
        $pathFragments = explode('/', $path);
        $filename = end($pathFragments);

        file_put_contents($saveDir . $filename, $content);
        echo "$filename saved." . "\n";
    }
}

?>