I'm interviewing for a company and they've given me a take home assignment that I have unlimited time to complete. One of the specifications is that I use a PHP API proxy to get around CORS for their API. I'm not permitted to use any PHP or JS libraries for this, aside from JQuery. I'm very new to PHP and am used to fetching data with React, so I feel a little out of my element. I've found what looks to me like it should be a solution here:
https://github.com/joseftw/php-rest-proxy
...but I can't get it to work. Whenever I load the page and check the console, it just stays <empty string> for both GET and POST requests (on Firefox). I know the calls are firing because they do perform console.log('test') if I add that. So then where's the data?
Here's the code for my PHP proxy file:
<?php
$url = $_REQUEST["url"];
if(!$url) {
echo "You need to pass in a target URL.";
return;
}
$response = "";
switch (getMethod()) {
case 'POST':
$response = makePostRequest(getPostData(), $url);
break;
case 'GET':
$response = makeGetRequest($url);
break;
default:
echo "This proxy only supports POST AND GET REQUESTS.";
return;
}
echo $response;
function getMethod() {
return $_SERVER["REQUEST_METHOD"];
}
function getPostData() {
return http_build_query($_POST);
}
function makePostRequest($data, $url) {
$httpHeader = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data));
return makePutOrPostCurl('POST', $data, true, $httpHeader, $url);
}
function makeGetRequest($url) {
$ch = initCurl($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
function makePutOrPostCurl($type, $data, $returnTransfer, $httpHeader, $url) {
$ch = initCurl($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, $returnTransfer);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
function initCurl($url) {
$httpHeader = array(
'Content-Type: application/x-www-form-urlencoded');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36');
return $ch;
}
?>
And here are my AJAX requests in my script.js file:
$(document).ready(function () {
$.ajax({
url: 'proxy.php?url=https://reqres.in/api/users',
type: 'POST',
data: { name: 'Zlatan Ibrahimovic' },
success: function (data) {
console.log(data);
},
});
$.get('proxy.php?url=https://reqres.in/api/users?page=2', function (data) {
console.log(data);
});
});
The endpoint I've provided is from a sample API and not the company's API. Still, I can't get the proxy/AJAX combo to work with anything. This is day 2 of this and I'm spinning my wheels. Can anyone point me in the right direction? Am I totally off-base with the PHP proxy setup, or is it something else?