I am trying to fetch from a service using jQuery and PHP (as a Proxy).
Here is my PHP that fetches the JSON.
<?php
if (!isset($_GET['url'])) die();
$url = urldecode($_GET['url']);
$url = 'http://' . str_replace('http://', '', $url);
echo file_get_contents($url);
?>
With the JS to manipulate the data (Sorry had to remove the key):
var api ='proxy.php?url=http://api.buycraft.net/v3?secret=MY-SECRET-KEY&action=payments';
$.getJSON(api, function(data){
$.each(data, function(i, donor){
console.log(donor);
});
});
So going to proxy.php?url=http://api.buycraft.net/v3?secret=MY-SECRET-KEY&action=payments
only returns the following:
{"code":100,"payload":[]}
But if I visit the JSON directly, I can see the data that I want
{
"code": 0,
"payload": [
{
"time": 1349661897,
"packages": [
"49381"
],
"ign": "notch",
"price": "15.99",
"currency": "USD"
}
For example.
And I know it's because php removes the ?action=payments
query. Even if I use &
instead of &
. So is there a way to keep PHP from removing the query from the URL?
Keep the API key in your php and don't expose it to client side in your javascript for obvious security reasons. You might just as well store the whole URL (other than proxy.php
) in your php config.
Also should implement use of CURL to retireve data. Allows for some error handling so you can send info back to client should API not be available
Try removing this from the backend PHP script:
$url = urldecode($_GET['url']);
PHP performs that automatically for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.