I have recently been studying CORS (Cross-Origin Resource Sharing) to help with removing barriers for competitor research activities such as fetching data, etc. Below is a very simple CORS proxy script. The PHP script fetches the contents of the URL, bypassing the CORS restriction and echo's the page's contents. It can be easily modded to sync with other scripts,
Code:
<!DOCTYPE html>
<head>
<title> Simple CORS Proxy Script</title>
<script>
function fetchProxy() {
const url = document.getElementById("url").value;
const proxyUrl = "cors_proxy.php?url=" + encodeURIComponent(url);
fetch(proxyUrl)
.then(response => response.text())
.then(data => {
document.getElementById("result").innerText = data;
})
.catch(error => {
console.error("Error fetching:", error);
});
}
</script>
</head>
<body>
<h1> Simple CORS Proxy Script</h1>
<input type="text" id="url" placeholder="Enter URL to fetch">
<button onclick="fetchProxy()">Fetch</button>
<pre id="result"></pre>
</body>
</html>
PHP:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: text/plain");
if (isset($_GET["url"])) {
$url = urldecode($_GET["url"]);
$options = [
"http" => [
"header" => "Content-Type: text/plain",
"method" => "GET"
]
];
$context = stream_context_create($options);
$content = file_get_contents($url, false, $context);
if ($content === false) {
http_response_code(400);
echo "Error fetching URL";
} else {
echo $content;
}
} else {
http_response_code(400);
echo "Missing 'url' parameter";
}
?>
Last edited: