Behaviour of PHP API change when sending json data - php

I've a php script who manage the connection of a user. When the connection is accepted by the script, a JSON web token is sent to the web service. The problem is, when I test my connection API with this web service, the script send me nothing without error. However, when i test it with postman, the script send me that token.
Here is my PHP script :
//Now create the TOKEN
$jwt = JWT::encode(
$data,
$secret_key,
$algorithme
);
$unencoded_array = ['jwt' => $jwt, 'admin' => $admin];
//echo "test";
echo json_encode($unencoded_array);
And here is my client call :
$rootScope.Connect = () => {
//Set params to request
var request = Global.url_api+'action=Connection&username='+$scope.username+
'&password='+$scope.pwd+
'&project='+$rootScope.project;
//Ask to the server if credentials is correct
$http.get(request)
.then((response) => {
console.log(response)
}
BUT, when i uncomment this
echo "test";
I receive my token with that string as you can see here :
Any idea ? if you need more information, please don't hesitate to ask.

Related

Can an XMLHTTPRequest capture form data, and be sent to a PHP cURL request to be posted?

I have a javascript file that captures form input, makes an XMLHTTP POST request with the input, and handles errors. I am currently POSTing to a separate PHP file, as the request requires sensitive API data and needs encoding. From the PHP file, I then send a cURL request to post the form input to the remote URL.
I want to handle errors based on the cURL response, but the XHR errors are different and take precedent over the cURL errors. Are both these requests necessary, or should I only be making either a single XHR or cURL request?
Whether or not both requests are necessary depends on your use case. Since yours sounds as they are indeed necessary, there's absolutely nothing wrong with it.
How you handle server-side errors client-side is also entirely up to you. For example, let's assume this pretty basic XHR handler, which sends some JSON data off to some endpoint and evaluates the response:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/endpoint.php');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = () => {
const status = xhr.status;
const response = JSON.parse(xhr.responseText);
if (status == 200) {
// Everything's fine
console.log(response.data);
} else {
// Some error occured
console.log(status, response.data);
}
};
xhr.send(JSON.stringify({}));
index.html
The above error handling strategy revolves around the HTTP status code received from the server, so we'll need to make sure they're send according to our needs:
/**
* In case an error occurred, send an error response.
*/
function error(string $message) {
// For properly returning a JSON response, see:
// https://stackoverflow.com/a/62834046/3323348
header("Content-type: application/json; charset=utf-8");
http_response_code(400); // HTTP status code - set to whatever code's appropriate
echo json_encode(['data' => $message]);
}
/**
* Send a response denoting a success.
*/
function success(array $data) {
// For properly returning a JSON response, see:
// https://stackoverflow.com/a/62834046/3323348
header("Content-type: application/json; charset=utf-8");
http_response_code(200);
echo json_encode(['data' => $data]);
}
// For proper error checking on JSON data, see:
// https://stackoverflow.com/a/37847337/3323348
$data = json_decode(file_get_contents('php://input'), true);
// Assume some processing happened. That result is either
// a success, or an error.
$success = mt_rand(0,1);
$success ? success($data) : error('An error occured.');
endpoint.php
Regarding cURL, you could easily change the last two lines to e.g.:
if(curl_errno($ch)) { // Assuming $ch is your cURL handle
error('Curl error: '.curl_error($ch));
}
else {
success($data);
}
Or you adapt the error function - if it would accept an array instead of a simple string, you'd be able to return more complex error data to your JavaScript client:
$curl_error = curl_errno($ch);
if ($curl_error) {
error([
'type' => 'cURL',
'no' => curl_errno($ch),
'message' => curl_error($ch)
]);
}
You don't have to stick with status codes for your error handling, though. You could send a JSON object back with one key denoting some successfully collected data, and one denoting an error if an error occurred. Or whatever suits your needs.

POST request does not arrive properly httpClient - ionic - php

I'm creating a REST API in PHP. The service login is:
<?php
include_once 'libs/Database.php';
header("Content-Type: application/json; charset=UTF-8");
Database::getPDO();
$myObj = null;
if ( Database::check($_POST['username'], $_POST['password']) ) {
$myObj = array('message' => "Verified", 'success' => true);
} else {
$myObj = array('message' => "Unauthorized", 'username' => $_POST['username'], 'success' => false);
}
$myJSON = json_encode($myObj);
echo $myJSON;
?>
And as you may see, I'm accessing $_POST global variable.
Postman: sending a POST request with header x-www-form-urlenconded and specifying the keys and values, the server does capture such keys.
Ionic: sending a POST request using HttpClient will not work. (The server captures null for both keys, username and password).
This is the code of the provider:
login(user, pass, url) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})
};
return this.http.post(url, "username="+user+"&"+"password="+pass, httpOptions);
}
I'm wondering how the body should be formatted, and according to this link should be like I have done (username=user&password=pass). By the way, all parameters are not null when the login function is called, hence, the problem is in the request.
For those of you interested, the answer of the server is:
{message: "Unauthorized", username: null, success: false}
Any help will be appreciated.
I'm copying my comment as an answer 'cause I want to post a photo.
Assuming you're using Angular's HttpClient, try to specify which type you're sending via POST: try to do something as this.http.post<string>(url, 'string', opts);.
I also suggest you to take a look at what you're sending as request via Chrome's Inspector (F12 on windows/linux, Cmd+Options+I on Mac), Network tab.
Obviously you must open it before sending request to be captured by DevTools. If you're debugging directly through the phone, on Windows/Linux you can use Remote Devices tab on Chrome's DevTools, or Safari on Mac.
An example using Chrome's DevTools:

How to test if a php post request with data from server (not directly from user) was successfully sent?

my task is to post data from server and not directly from a user(with its ip address). i hope you can help! :)
Code first:
<?php
add_action('init', function() {
if (isset($_POST['form_submitted'])) {
$data = ($_POST);
// send data via post request to server
$destinationUrl = getenv('VALIDATION_URL_DESTINATION'); // get URL from enviromnent variable
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($destinationUrl, false, $context);
// if status code 200
if ($http_response_header[0] == "HTTP/1.1 200 OK") {
echo "<p>Post data successfully sent.</p>";
} else {
// if status code not 200 -> wp_mail()
$to = getenv('VALIDATION_EMAIL'); // get email adress from enviromnent variable
wp_mail($to, "", strip_tags("Post data could not be sent."), "");
// redirect to form and display error message
}
}
});
?>
By submitting a form I get some date through a php request. I would like to send this data to a certain destination url and email myself if the status code is not "200" and display an error message to the last visited page (form.php).
I have certain questions:
How can i test locally if my code is correct and really sends the data trough a post request? Do I have to use a second server to test it? (I work with valet or mampp and wordpress)
How can I force the script to display a message on the last visited page?
How can a third person knowing about the structure the data was sent access to the data? For example: He/She fills out the form and submits. If the data was successfully sent it be nice if the data were in a certain format like
?first_name=lorem&last_name=ipsum&...

How to set up Google+ Sign-In for server-side apps for a website?

I am trying to add a sign in with google+ button on my website just to retrieve basic information.
but the documentation doesnt seem to make any sense to me.
(https://developers.google.com/+/web/signin/server-side-flow)
it appears out of date and not complete and there seems to be various api library's that can be used.
Can anyone explain all this more clearly or tell me how i should go about making this work and which api library to use etc?
a full sample with code would be very helpful.
thanx
Ok so i will add more detail. google development page gives this as an example for a login button :
<html>
<head>
<!-- BEGIN Pre-requisites -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script src="https://apis.google.com/js/client:platform.js?onload=start" async defer>
</script>
<!-- END Pre-requisites -->
</head>
<body>
<div id="signinButton">
<span class="g-signin"
data-scope="https://www.googleapis.com/auth/plus.login"
data-clientid="your-client-id"
data-redirecturi="postmessage"
data-accesstype="offline"
data-cookiepolicy="single_host_origin"
data-callback="signInCallback">
</span>
</div>
<div id="result"></div>
<script>
function signInCallback(authResult) {
if (authResult['code']) {
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');
// Send the code to the server
$.ajax({
type: 'POST',
url: 'plus.php?storeToken',
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response if necessary.
// Prints the list of people that the user has allowed the app to know
// to the console.
console.log(result);
if (result['profile'] && result['people']){
$('#results').html('Hello ' + result['profile']['displayName'] + '. You successfully made a server side call to people.get and people.list');
} else {
$('#results').html('Failed to make a server-side call. Check your configuration and console.');
}
},
processData: false,
data: authResult['code']
});
} else if (authResult['error']) {
// There was an error.
// Possible error codes:
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatially log in the user
// console.log('There was an error: ' + authResult['error']);
}
}
</script>
</body>
</html>
but it also provides:
<?php
// Create a state token to prevent request forgery.
// Store it in the session for later validation.
$state = md5(rand());
$app['session']->set('state', $state);
// Set the client ID, token state, and application name in the HTML while
// serving it.
return $app['twig']->render('index.html', array(
'CLIENT_ID' => CLIENT_ID,
'STATE' => $state,
'APPLICATION_NAME' => APPLICATION_NAME
));
// Ensure that this is no request forgery going on, and that the user
// sending us this connect request is the user that was supposed to.
if ($request->get('state') != ($app['session']->get('state'))) {
return new Response('Invalid state parameter', 401);
}
$code = $request->getContent();
$gPlusId = $request->get['gplus_id'];
// Exchange the OAuth 2.0 authorization code for user credentials.
$client->authenticate($code);
$token = json_decode($client->getAccessToken());
// Verify the token
$reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' .
$token->access_token;
$req = new Google_HttpRequest($reqUrl);
$tokenInfo = json_decode(
$client::getIo()->authenticatedRequest($req)->getResponseBody());
// If there was an error in the token info, abort.
if ($tokenInfo->error) {
return new Response($tokenInfo->error, 500);
}
// Make sure the token we got is for the intended user.
if ($tokenInfo->userid != $gPlusId) {
return new Response(
"Token's user ID doesn't match given user ID", 401);
}
// Make sure the token we got is for our app.
if ($tokenInfo->audience != CLIENT_ID) {
return new Response(
"Token's client ID does not match app's.", 401);
}
// Store the token in the session for later use.
$app['session']->set('token', json_encode($token));
$response = 'Succesfully connected with token: ' . print_r($token, true);
?>
But it doesnt say where to put that last bit of code or how to refer to an api library or where to put the secret or anything. so i could do with some pointing in the righ direction please?
ok so if anyone else is having trouble.
i followed the tutorial on this link
I downloaded the api library from there, changed the configs file and used the example that is provided and it worked fine.
to make it work on a localhost you have to set your Authorized JavaScript origins to a localhost:# for example http://localhost:12345
then to make your browser accept the folder or the signin page in command prompt type in
cd c:/the/path/of/the/downloaded/api/example
then type in:
php -S localhost:12345
hope that helps anyone

IBM Worklight - How to access JSON sent using an adapter in server-side PHP?

I am developing a hybrid application in IBM Worklight.
In my app, there is a registration form. I have a requirement: After the user registers with the app, the form data will be sent to an external server in JSON format using an HTTP adapter.
In the external server,
How to access the JSON data sent using the HTTP adapter in a PHP file? and
How to send back a response in the same JSON format?
Please give demo codes of both HTTP adapter and server side PHP code.
Client code:
function callAdapter(){
var invocationData = {
adapter : 'MyAdapter',
procedure : 'MyAdapterProcedure',
parameters : [username, password]
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : adapterSuccessCallback,
onFailure : adapterFailureCallback
});
}
Adapter implementation:
function myAdapterProcedure(username, password) {
var credentials = JSON.stringify({username: username, password: password});
var input = {
method : 'post',
returnedContentType : 'json',
path : "/myPHPscript.php",
parameters: {credentials: credentials}
};
return WL.Server.invokeHttp(input);
}
PHP script:
<?php
$jsonObj = $_POST['credentials'];
$credentials = json_decode($jsonObj)
// sanitation, database calls, etc
$returnDict = array();
$returnDict["success"] = true;
echo json_encode($returnDict);
?>

Categories