Bypass cors restrictions in javascript with PHP

Problem

Modern Browsers don't allow you to send requests to another website that don't have the Cross-Origin Header set.
So if you want to get resources from another server then you would sooner or later run into problems.

My specific problem:
I wanted to write a browser-based viewer of someone's REST API. I couldn't get them via a Javascript request, but I could get them with other programming languages.

Also, please try to ask for permission before grabbing someone else's data!

Solution

PHP doesn't care about Cross Origin requests and is easy to setup.

For my problem I built myself a small "PHP Fetcher" to simply get the Resource and echo it as a response.
This way I can simply write a Javascript Request to my own Server and get the response without many more workarounds.

The PHP code I settled on:

Filename: t.php
Full Content:

<?php
$json = file_get_contents('https://example.com/api/v1/status?key=XXX&server='.$_GET['id']);
$arr = json_decode($json, true); //Accessible Array from JSON answer
echo $arr['response']['serverstatus'];
?>

Now I can simply make an ajax call from javascript and access this resource over my own PHP file:
Javascript:

return $.ajax({
  type: "GET",
  url: "https://myserver.com/t.php?id="+id
}).done(function(data) {
  document.body.innerHTML += data+"<br>";
});

This works well for my needs and is a quick and easy fix for my problem.
Warning: This is NOT made for production. Do not spam or abuse a service with this.

This mini-php-script is not optimized. There is neither a rate-limit nor caching.
With caching you would relieve the strain on the target API and optimize your service.
With rate-limits you would secure your own service from getting into trouble for spamming other services.