$_REQUEST/$_POST is printing an empty array for Webservice - php

I am receiving Web Service from iOS device. But when I try to print the request that I have received I get data as empty.
Input Sent from iOS device as Service. It is sent as POST from iOS:
{"AccessToken"={"Mykey":"test123"}
Code in my PHP Page:
foreach($_REQUEST as $value)
{
$xml_content_array = trim($value);
}
What else I have tried:
if(empty($xml_content_array) === true)
{
$xml_content_array = trim($HTTP_RAW_POST_DATA);
}
Even $HTTP_RAW_POST_DATA is not printing anything. Also tried the below:
file_get_contents('php://input');
Did not work.
I am pretty sure the data is coming from the iOS end but I am unable to capture the POST request.
Thanks in advance

This should work
$access_token = $_POST["AccessToken"];
echo $access_token;

Related

Problem parsing the body of a POST request

So what I'm trying to do is: with a link similar to: http://localhost/API-REST/Endpoints/ajoutDeMessage.php?contenu='Hello'&idUser=4. For now, I'm only testing my request with Postman. So I'm putting this URL directly in Postman, and press send.
When I'm doing a request without a body, it works fine.
So, I need to send a string and an id through the URL, and with a function, I'm inserting these data in my database.
With the php://input, I expect to have the variables contenu and idUser in the body for a SQL request.
What I want to do next is a React app which will communicate with the API (but that's not related for now).
So here is my code:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require_once('../Configuration/database.php');
require_once('../Users/messages.php');
$database = new Database();
$db = $database->getConnection();
$json = json_decode(file_get_contents("php://input"),true);
var_dump($json);
if(!empty($json->contenu) && !empty($json->idUser)){
$contenu = strip_tags($json->contenu);
$idUser = strip_tags($json->idUser);
$message = new Messages($db);
if ($message->addMessage($contenu,$idUser)){
http_response_code(201);
$response['message'] = 'GOOD ENTRY';
}else{
http_response_code(400);
$response['message'] = 'BAD ENTRY';
}
}else{
http_response_code(400);
$response['message'] = 'INCOMPREHENSIBLE DATA';
}
echo json_encode($response);
} else {
http_response_code(405);
$response['error_code'] = 405;
$response['message'] = 'BAD REQUEST TYPE';
echo json_encode($response);
}
There is no post body
i'm putting this url directly in postman, and press send.
I don't use postman myself, but doing this will generate a post request with no data it's the equivalent of:
curl -X POST http://example.com
That's not passing a post body at all. The intent is more like:
curl http://example.com
-H 'Content-Type: application/json'
-d '{"contenu":"Hello","idUser":4}'
This is why file_get_contents("php://input") doesn't return anything.
Note that html form data is available via $_POST - but only for urlencoded POST bodies (which I understand not to be the intent of the question).
Where is the data?
i'm putting this url directly in postman, and press send.
Returning to this quote, the only place for the data is in the url - that is not the normal way to pass data with a post request.
Url arguments are available via $_GET, with the url in the question this code:
<?php
var_dump($_GET);
will output:
array(2) {
["contenu"]=>
string(7) "'Hello'"
["idUser"]=>
string(1) "4"
}
A detail, but note the string includes the single quotes which are in the url (that are probably not desired).
What's the right way to do this?
With a request being made like this:
curl http://example.com
-H 'Content-Type: application/json'
-d '{"contenu":"Hello","idUser":4}'
That data can be accessed like so:
<?php
$body = file_get_contents('php://input');
$data = json_decode($body, true);
$jsonError = json_last_error();
if ($jsonError) {
print_r(['input' => $body, 'error' => json_last_error_msg()]);
exit;
}
echo $data['contenu']; // Hello
echo $data['idUser']; // 4
...
This is very similar to the code in the question, the error appears to primarily be how the request is being made rather than the php logic.

can't get right api result from json (using json_decode)

I want to print result from API...
But it is not working... I don't know what is wrong I tried to do it but got this and it is not working:
<?php
$api = 'https://api.battlemetrics.com/servers/'; // the main API for servers.
$server = '5090469'; // the number of the server you will get the info from most of thime something like 5484856.
$api_full = $api . $server; // bringing them together.
$json = file_get_contents("$api_full"); // Putting the content of the file in a variable.
$response = json_decode($json, true); // decode the JSON feed
if ($response['data']['status'] == "online") {
echo "ONLINE";
} else {
echo "OFFLINE";
};
?>
Extra if you want to see the json response this is the link: https://api.battlemetrics.com/servers/5090469
Thanks in advance for your tips and help.
Looks like you are just missing a key in your if statement.
It should be:
if($response['data']['attributes']['status'] == "online")

Slack Events PHP Response

I'm working on an integration between Slack and Filemaker utilizing PHP. I am successful in having the code create a record in Filemaker based on the json request, and also have no trouble returning the challenge key to Slack.
However, I'm having trouble passing the header response 200 OK to Slack, while passing the challenge back. It looks like it has to be one or the other.
I've tried to move the HTTP header to different areas in the code, but haven't had any success so far.
Here is the current code:
<?php
$data = json_decode(file_get_contents('php://input'), true);
if (!isset($data["challenge"])) {
$body = $_SERVER['HTTP_X_SLACK_RETRY_REASON'];
require_once ('Filemaker.php');
//$body = file_get_contents('php://input');
$fm = new Filemaker();
$fm->setProperty('database', '');
$fm->setProperty('username', '');
$fm->setProperty('password', '');
$command = $fm->newPerformScriptCommand('PHP_RESPONSE', 'script', $body);
$result = $command->execute();
}
else {
header("Content-Type: text/plain");
header('X-PHP-Response-Code: 200', true, 200);
echo $data["challenge"];
}
?>
The result I expect is for the code to return the challenge code for Slack, while also returning an HTTP header of 200 OK.
Currently I can see I am receiving an error of "http_error" from Slack, which is what leads me to believe the problem is that the header is not being passed back successfully.
Any ideas on what is wrong, or suggestions on the right direction to proceed would be greatly appreciated.
The problem was occurring because for events slack doesn't send "challenge" as a parameter when sending events. It looks like echoing "challenge" is only needed when initially setting the URL for the events API.
I enclosed the challenge echo in a if statement that would only trigger if the challenge variable was present. After doing so the 200 OK was successfully passed.
Here is the code I used that solved the problem for me:
$data = json_decode(file_get_contents('php://input'), true);
if (isset($data["challenge"])) {
$message = [
"challenge" => $data["challenge"]
];
header('Content-Type: application/json');
echo json_encode($message);
}
The documentation is actually a bit inconsistent on this topic. It claims you can respond the challenge in plan text, but the example shows it as x-www-form-urlencoded.
To be on the safe side try returning the challenge as JSON. That works perfectly for me. You also do not need to explicitly set the HTTP 200 code.
Example code:
$message = [
"challenge" => $data["challenge"]
];
header('content-type: application/json');
echo json_encode($message);

Push notification is being sent to server but doesn't appear on cellphone

So i have this test application that i'm using to learn how to send push notifications from an external server hosted in my desktop to a virtual device or smartphone.
Then I use a simple form and input title and message and click the submit button to send the notification.
I have triple checked, the encoding of the notification is fine, and I'm able to pass the firebase token from the android app to the server, which stores it in the MySQL database.
Also the app is correctly sending the token and the server_key is also correct (used the built in copy function at firebase website)
Why isn't my notification showing? this is the source code of the script in php to send the notification to firebase:
<?php
require "init.php";
$message = $_POST['message'];
$title = $_POST['title'];
$path_to_fcm = 'https://fcm.googleapis.com/fcm/send';
$server_key = "AAAA0Tedu0Y:APA91bGF1k9LAVw90LVM9IdWludKeG1ueVo2V7HesN4CVz2KFvcwGvLkDymuHjm0IvfRvZ6wOEu5Q33pBgYDUXopvTOBSDKQJf2zFFp_22gTCrg6zxNxKyw8_0M9ciPLt3YyJOwkmNYR";
$sql = "select fcm_token from fcm_info";
$result = mysqli_query($con,$sql);
//these lines get the key that has been store (i only store one key from one app, so it takes the first value of the result
$row = mysqli_fetch_row($result);
$key = $row[0];
$header = array(
'Authorization:key=' .$server_key,
'Content-Type:application/json'
);
$field = array( 'to'=>$key,
'notification'=>array('title'=>$title,'body'=>$message)
);
$payload = json_encode($field);
//If echo $payload, It print the following:
/*
{
"to":"esM8_IMRWrw:APA91bEVOTjpC5kkqAWqWwEs7gNq5-4iUvL6fC947cfWkg1G0VhKDiuibSOr_xSNcIJ8rb4VewjNJ2Jd_0AXBdQgTbOO0FO-stmP3ymOCLGQlka3s2RQ3854UiPr_puc274hXSlQMLen",
"notification":{
"title":"asdasd",
"body":"asdasd"
}
}
So the json is properly formatted
*/
/*this generates the http url connection from my server to firebase push notification sending url. I think the error is somewhere in these lines, but i dont know where*/
$curl_session = curl_init();
curl_setopt($curl_session,CURLOPT_URL,$path_to_fcm);
curl_setopt($curl_session,CURLOPT_POST,TRUE);
curl_setopt($curl_session,CURLOPT_HTTPHEADER,$header);
curl_setopt($curl_session,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl_session,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($curl_session,CURLOPT_IPRESOLVE,CURL_IPRESOLVE_V4);
curl_setopt($curl_session,CURLOPT_POSTFIELDS,$payload);
$result = curl_exec($curl_session);
curl_close($curl_session);
mysqli_close($con);
?>
Any help is appreciated, thanks in advance!
Check this link to get more information about push notifications
How to handle notification when app in background in Firebase

Pubsubhubub to get "POST" response from the hub

I'm trying to use Pubsubhubub to get real time RSS feeds update. I'm using PHP for that purpose.
I subscribed to thenextweb as an example;
$hub_url = "http://pubsubhubbub.appspot.com/";
$callback_url = "http://xx.com/rss/callback.php";
$feed = "http://feeds2.feedburner.com/thenextweb";
$sub = new Subscriber($hub_url, $callback_url);
$status = $sub->subscribe($feed);
I receive The hub returns code 202, and after that a "GET" response to my callback.php with the hub_challenge and other stuff. I followed what the tutorials suggest of echoing this number, and hence, the hub will be able to push updates to my callback.
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe') {
$challenge = $_GET['hub_challenge'];
header('HTTP/1.1 200 "OK"', null, 200);
header('Content-Type: text/plain');
echo $challenge;
}
That's how I echo the challenge number. The problem here is that I don't get any other messages from the hub even though i have a condition to handle any POST message in my callback.
else if ($method == 'POST') {
$updates = json_decode(file_get_contents("php://input"), true);
//doing stuff with the data here
}
I'm not sure if the problem is with the echo part or after that. Does anyone have similar issues? what am I doing wrong?
I just solved the problem. Apparently I was using a different topic_url, I was using this link: http://feeds.feedburner.com/TheBoyGeniusReport?format=xml. Instead, view the page source and make sure you are using the link inside href. The highlighted link below is what you're supposed to use.
... xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/TheBoyGeniusReport"...

Categories