Created
May 25, 2011 22:30
-
-
Save bradfordcp/992145 to your computer and use it in GitHub Desktop.
PHP Proxy to a specified domain, used for retrieving .atom feeds from shopify and avoid cross-domain issues.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Location where we are storing the cache | |
$CACHE_DIRECTORY = dirname(dirname(__FILE__)) ."/statics"; | |
// Set the lifetime of cached pages | |
$CACHE_LIFETIME = (24 * 60 * 60); // 24 Hours * 60 Minutes (per hour) * 60 Seconds (per minute) | |
// Grab the URL to proxy, strip out the host as a security measure | |
$url = null; | |
$start = strpos($_SERVER['REQUEST_URI']); | |
if ($start !== FALSE) { | |
$url = substr($_SERVER['REQUEST_URI'], $start + 4); | |
} | |
else { | |
header("HTTP/1.0 400 Bad Request"); | |
echo "Missing parameter URL"; | |
exit(); | |
} | |
$cached_file = $CACHE_DIRECTORY . str_replace('.atom', '.xml', $url); | |
$cache_invalid = FALSE; | |
if (file_exists($cached_file) && $cache_mtime = filemtime($cached_file)) { | |
$cache_invalid = time() - $cache_mtime > $CACHE_LIFETIME; | |
} | |
else { | |
$cache_invalid = TRUE; | |
} | |
if ($cache_invalid) { | |
// Request the page and update the cache prior to redirecting | |
$remote_url = "http://shop.liftcaregiving.com". $url; | |
$ch = curl_init($remote_url); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); | |
$resp = curl_exec($ch); | |
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE); | |
if ($status == 200) { | |
// Verify the directory for the cache exists | |
$parts = explode('/', $cached_file); | |
array_shift($parts); | |
array_pop($parts); | |
$path = '/'. implode("/", $parts); | |
if(!file_exists($path)) { | |
// Create the directory | |
if(!mkdir($path, 0775, TRUE)) { | |
header("HTTP/1.0 500 Internal Server Error"); | |
echo "FAILED TO WRITE CACHE Directory: Could not make directory '$path'"; | |
exit(); | |
} | |
} | |
// We have a valid response cache it | |
$fh = fopen($cached_file, 'w'); | |
if ($fh === FALSE) { | |
header("HTTP/1.0 500 Internal Server Error"); | |
echo "FAILED TO WRITE CACHE: Could not open file '$cached_file'"; | |
exit(); | |
} | |
else { | |
fwrite($fh, $resp); | |
fclose($fh); | |
} | |
} | |
else { | |
header("HTTP/1.0 ". $status); | |
echo "Remote Error Encountered"; | |
exit(); | |
} | |
} | |
// Redirect to the cached page | |
$cache_url = 'http://'. $_SERVER['HTTP_HOST']. '/statics'. str_replace('.atom', '.xml', $url); | |
header("Location: ". $cache_url); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment