Skip to content

Instantly share code, notes, and snippets.

@kabeer11000
Forked from hubgit/cache-proxy.php
Created March 2, 2021 18:59
Show Gist options
  • Save kabeer11000/8ec1abb70c82d45b0b1c8cf8b3a76afd to your computer and use it in GitHub Desktop.
Save kabeer11000/8ec1abb70c82d45b0b1c8cf8b3a76afd to your computer and use it in GitHub Desktop.
PHP caching proxy
<?php
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: accept, x-requested-with, content-type');
exit();
}
$url = $_GET['url'];
$file = __DIR__ . '/../app/data/' . hash('sha256', $url);
function output_headers($file) {
$info = json_decode(file_get_contents($file . '.json'), true);
http_response_code($info['http_code']);
header('Access-Control-Allow-Origin: *');
header('Content-Type: ' . $info['content_type']);
header('Content-Length: ' . filesize($file));
//header('Content-Length: ' . $info['download_content_length']);
}
if (file_exists($file)) {
output_headers($file);
readfile($file);
exit();
}
$headers = getallheaders();
$output = fopen($file, 'w');
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_ENCODING, '');
curl_setopt($curl, CURLOPT_HTTPHEADER, array_map(function($value, $key) {
if (!in_array($key, array('Origin', 'Referer', 'Connection', 'Host'))) {
return $key . ':' . $value;
}
}, $headers, array_keys($headers)));
curl_setopt($curl, CURLOPT_FILE, $output);
curl_exec($curl);
file_put_contents($file . '.json', json_encode(curl_getinfo($curl), JSON_PRETTY_PRINT));
curl_close($curl);
fclose($output);
output_headers($file);
readfile($file);
exit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment