Last active
August 8, 2024 17:50
-
-
Save hubgit/11212195 to your computer and use it in GitHub Desktop.
PHP caching proxy
This file contains hidden or 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 | |
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