How to hide api key using php? - javascript

everyone. I'm trying to create league of legend api, but I need to hide the api key. I know there is no way to hide the key from the front-end, so this is how I did it, I'm not sure this is the best way to do it. Please help me!! Thanks!
HTML.file
var getID = function(playerName) {
$.ajax({
type: "POST",
url:"test.php",
dataType:'json',
data: {'url': "api/lol/na/v1.4/summoner/by-name/"+playerName+"?"},
success: function(data){
playerID = data[playerName].id;
console.log(playerID);
}
});
};
So every time I'm calling ajax, I'm making a ajax request to the test.php file, and pass the url to it, then the php code will use the url to get request from the game server and send back the result to front-end.
test.php
<?php
header('Content-Type: application/json');
$url = $_POST['url'];
$json = file_get_contents('https://na.api.pvp.net/'.$url.'api_key=key');
$obj = json_decode($json);
echo json_encode($obj, JSON_PRETTY_PRINT);
?>

As long as the Ajax request will only trigger for a valid, authenticated user with an established session this looks good. Otherwise, anyone could call it with arbitrary 'playerNames'.
It will definitely prevent your API key from being exposed.

Related

AJAX sending data in GET request is not working

I have an AJAX function running from my frontend looking like this:
//api.js
function getTransactions(authToken) {
$.ajax({
type: 'GET',
data: {
'authToken':
'ACE8166BCD0F5B8FB5FF693F3B4056160D957A0E57FC9912EE70E9231D03166B9661BCB96BD678F3BD65CFD6DA651F1E5B5D28E294CA88C0EEE2B3C7093699EAA731409A1F8DA5C772E2335EC67ED410E20ED9FBB35B6918804879BE3D3FE1329F2348F1FB83B9BC4992F7EA75D1ED4A4F9A684371CB0D0CF09E131ADAB905CAE4454C4C9D81A9A48B05AA77B4D6F7D7C5A596C021DA368F6E356A5750EB2D117C8E02782731F7641526ACBA061EEDDB2339EABB3B179F39738D8AEF4510E612A2D11BCC74D67C3C4D989A86BB9EE710342042D2A71A364B0D17D799E28D51458AD44F53F3930E31387FF52BAD141D4AA467384282226AB2B1B55A5B45CCAF5F61DDAD770E3BA9210BBE7B926BD594F52F17F053B6C0366B4CDC4F2F147648A545ABDDD854FF778F4EA0A2672E0D249B',
},
crossDomain: true,
dataType: 'JSON',
url: 'http://localhost:8000/transactions',
}).done(function (data) {
.....
I have been trying to pass the authToken parameter to the data object, and then retrieve it in the PHP backend using (case transactions):
//index.php
$request = $_SERVER["REQUEST_URI"];
switch ($request) {
case "/login" :
require __DIR__ . "/login.php";
$userEmail = $_POST["userEmail"];
$userPassword = $_POST["userPassword"];
echo login($userEmail, $userPassword);
break;
case "/transactions" :
require __DIR__ . "/transactions.php";
$authToken = $_GET["authToken"];
getTransactions($authToken);
break;
}
If I hardcode the authToken into the getTransactions function inside case "/transactions", it works fine.
(EDIT: even if I hardcode the token in index.php, if I also hardcode it into the AJAX function (which shouldn't matter), the whole process doesn't return any data).
But there's something, either in the $_GET() in index.php, or in the AJAX function that it preventing the data from getting into the getTransactions function in index.php.
I have tried putting strings around the authToken key in the data object, also using the authToken parameter, as well as JSON.stringify-ing the data object. Further, I have changed/removed the dataType, and exhausted every other method suggested by stack overflow and other websites.
This is especially difficult because it's my first time using PHP, and I don't know how to show echos in my terminal, so I can't see any output from the PHP files.
Any help would be appreciated.
as #CBroe said, the authToken query parameter was messing with the routing for /transactions. What I did was add this code to my $request variable:
$request = strtok($_SERVER["REQUEST_URI"], "?");
the strtok() function allowed me to strip off the end of the URI before the ?, and the /transactions case was read properly.
Thanks CBroe!

Angular - send HTTP post data to server [HOW TO]

I'm trying to send data from my login FORM to backend writen in PHP using POST method.
my Angular code looks like:
$scope.getToken = function(){
// console.log $scope.login to make sure I'm not sending empty data
console.log($scope.login);
$http({
method: 'POST',
url: '../../api/v1/Oauth.php',
data: { 'login' : $scope.login, 'password' : $scope.password }
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
};
and after that I try to catch it on my PHP:
if((isset($_POST['login']) AND isset($_POST['password'])))
{
$username = $_POST['login'];
$password = $_POST['password'];
echo $username;
}
else
var_dump($_POST);
This statement always go to else and return empty array.
Can someone advise me what I'm doing wrong or how can I debug this?
Because it looks that I send data fron angular correctly but it didn't come to server.
Thanks
Kind Regards
Andurit
Use this:
json_decode(file_get_contents('php://input'));
Check your network tab in your developer bar. You can see that you send payload data in the http body. That's why the $_POST array is empty.
Some older server side web libraries like Coldfusion/.NET/PHP have issues grabbing a POST BODY by default (which is how $http sends the data).
You can reference How to get body of a POST in php? to learn how to write your PHP in a way that it will accept the current and correct standard of sending data via a post.
To access the entity body of a POST or PUT request (or any other HTTP
method):
$entityBody = file_get_contents('php://input');
Also, the STDIN constant is an already-open stream to php://input, so
you can alternatively do:
$entityBody = stream_get_contents(STDIN);
try:
data: { login : $scope.login, password : $scope.password }
$http.post('url', {login: 'Alex', password: 'qwerty'}).then(function(){},function(){});

saving json data to json file using ajax PHP

My json file looks like this:
count_click.json
[
{
"link": "google.com",
"count": 2
},
{
"link": "yahoo.com",
"count": 3
}
]
now I open this file using
$.getJSON('count_click.json',function(data){
// do something with data
var stringData = JSON.stringify(data);
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'http://127.0.0.x:3xx9/update.php',
data: {stringData: stringData},
success : function(d){
alert('done');}
})
}) // end of getJSON function
update.php
<?php
$a = file_get_contents("php://input");
file_put_contents('http://127.0.0.x:3xx9/count_click.json', json_encode($a));
?>
I get error in the browser console:
POST http://127.0.0.x:3xx9/update.php 404 (Not Found)
But the file is there. When I go to this http://127.0.0.x:3xx9/update.php in the browser, I see the contents of the php fine perfectly fine.
You could edit your PHP:
<?php
$a = $_POST['stringData'];
// you should check $a consists valid json - what you want it to be
file_put_contents('count_click.json', $a);
You really should check that posted data to be valid and not saving something unwanted. Also you could check that request really is POST -> $_SERVER['REQUEST_METHOD'].
Maybe you find some other methods to improve security (for example only allow post from own domain...).
A few problems.
file_get_contents("php://input"); Why? You are already sending a Post with data, no need to complicate things with a stream.
Also file_put_contents needs the path to the actual file on disk, not a URL!
data: {stringData: stringData} from your AJAX request means you can access it on your server with $data = $_POST['stringData'];.
Simply echo something out to see if you are actually getting anything.
echo json_encode( array("Payload" => $_POST['stringData']) );
If that doesn't work, try accessing the endpoint with your browser (not the file as that does not need PHP for the browser to read it).
Point your browser to http://127.0.0.x:3xx9/update.php and on your server, simply
echo "Request received!";
If you see that in your browser, your endpoint is working and you can continue troubleshooting. If you don't, then this is beyond JS and PHP and probably has to do with your server's settings. If you are using RStudio's Shiny Server, then that does not work for PHP
In any case, your endpoint should always return something when called. Not just save the file. It is just good practice.
header("HTTP/1.1 200 OK");

JQuery $.ajax request returns me "Error 404" even if the resource exists

I'm developing an app with TideSDK and I need to send some data to a PHP script that will create a file to store it on the pc. I'm pretty new to AJAX and to send data I do:
var jsonString = JSON.stringify(GW2.items);
$.ajax({
url: "/assets/scripts/save.php",
type: "post",
dataType: "json",
data: { jsonString: jsonString }
}).done(function(data){
console.log(data);
});
Where GW2.items is a JSON object, "save.php" is my script and jsonString is the variable I want to send.
But, when I try to execute the program it returns me:
POST http://127.0.0.1:52432/assets/scripts/save.php 404 Not Found
And the answer is: Cannot POST /assets/scripts/save.php
This is the PHP script:
<?php
$jsonString = $_GET['jsonString'];
return {};
?>
I checked the path and it's correct so why it can't find my file?
Did you try your path with POST or just GET? It could be exist for GET requests (pasting the url on a browser) but probably not for POST or other HTTP verbs.
You can use REST clients like Postman to be sure, which is also a Chrome extension.

POST Request PHP equivalent in AJAX / JQuery

I'm able to send some POST requests to a php file. On this php file, I use this to check if my POST request is what I want:
<?php
if(isset($_POST['message'])) {
// Some stuff here
}
?>
I would like to know if I can do the same thing in AJAX / JQuery ?
Not something like this:
<script>
$.post("page.php", $("form[name=addMessage]").serialize(), function(data) {
//Do something here
}).error(function() {
//error
})
</script>
EDIT:
I don't want to send POST request in AJAX / JQuery. I just want to check if I receive a POST request, send from another page.
Indeed, I send a POST request with a field named "message". And I my question is: Is it possible to check if the field "message" is set, but not in PHP, in AJAX / JQquery.
Thank you so much for your help.
Regards,
Lapinou.
If I understand what you are trying to do: No.
Do you want to just listen for an incoming request in Javascript without calling any Ajax-methods? This is not possible. Javascript needs to be told that "I am sending a request now, and I want a response". It is not possible to say "If any request is sent, deal with it here".
Think about it. How would this work? If Javascript would listen to any request incoming, how would it know the difference between an user submitting a form and you sending a request using Postman?
Also, once you load the website in your browser, this is said to be clientside. Everything that happens after that is bound to your computer and your instance of the website. Any request sent to the site would be sent to the server, not your browser.
An other way of doing a post is this:
$.ajax({
type: "POST",
url: "page.php",
cache: false,
data: "message=" + $(".msgBox").val(), //Or Json format { "message" : $(".msgBox").val() },
success: function(html){
$(dashboard_id).html(html);
}
});
Try this:
$("form[name=addMessage]").submit(function(e) {
e.preventDefault();
$.post("page.php", $(this).serialize(), function(data) {
//Do something here
}).error(function() {
//error
})
});
*Update
As per your comment you want to check POST value using JavaScript / jQuery, I don't think so you can access POST data using JavaScript / jQuery. But you want to mix php then you can do something like this
var post = '<?php json_encode($_POST); ?>';
if (post.message !== undefined) {
}
You have to put var post = '<?php json_encode($_POST); ?>'; in a php file

Categories

Resources