POST data not received on server side - php

I use Postman (the Chrome app) to send POST data to a URL but the POST data are never received by the PHP file, no matter how I change the content-type before sending. Is there a server setting on Apache that stops post data from external sources?
This is the URL:
http://friendesque.com/arranged/handler.php
And this is the content of the handler.php file:
<?php
echo("Inside file");
echo("JSON:");
$json = file_get_contents('php://input');
echo($json);
echo("POST:");
print_r($_POST);
echo("GET:");
print_r($_GET);
?>

In order for data to be available in $_POST array, the following conditions should be met:
Request must be sent with POST HTTP method
Content-Type header must be set to application/x-www-form-urlencoded
Request payload (body) must be in the form of URL-encoded parameters, e.g.
param1=a&param2=b
I sent to your URL a request that meets those 3 conditions and got my data available in $_POST array.

Use file name like /index.php . It will work !!

Related

How to get webhook response data using tradingview and php

I'm trying to get Tradingview signals to my remote php script using webhook and trading view alerts. I can't succeed . I'm following this way
In my trading view strategy I have this
strategy.entry("Long", strategy.long, alert_message = "entry_long")
strategy.exit("Exit Long", "Long", limit=LONG_take_profit, stop=LONG_stop_loss, alert_message = "exit_long")
then I set the alert as follow
Then I set a PHP script as follow to receive the POST curl JSON data from Trading view
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// fetch RAW input
$json = file_get_contents('php://input');
// decode json
$object = json_decode($json);
// expecting valid json
if (json_last_error() !== JSON_ERROR_NONE) {
die(header('HTTP/1.0 415 Unsupported Media Type'));
}
$servdate2 = time();
$servdate=date('d-M-Y H:i:s',$servdate2);
file_put_contents("/home/user/public_html/data.txt", "$servdate :".print_r($object, true),FILE_APPEND);
}
I receive the alert via email correctly but I do not receive data in /home/user/public_html/data.txt . What am I doing wrong ? How to send the Tradingview JSON data to my remote PHP script ?
I'm not familiar with PHP, but you've asked:
How to send the Tradingview JSON data to my remote PHP script ?
Your alert message as it is currently written in the alert_message argument, is not valid JSON and therefore it is sent as a txt/plain content type. If you want the alert to be sent as application/json you will need to have it in a valid JSON.
Webhooks allow you to send a POST request to a certain URL every time the alert is triggered. This feature can be enabled when you create or edit an alert. Add the correct URL for your app and we will send a POST request as soon as the alert is triggered, with the alert message in the body of the request. If the alert message is valid JSON, we will send a request with an "application/json" content-type header. Otherwise, we will send "text/plain" as a content-type header.
You can read more about it here.
EDIT:
You can make minor adjustments to your code, and it will be sent as JSON:
strategy.entry("Long", strategy.long, alert_message = '{"message": "entry_long"}')
strategy.exit("Exit Long", "Long", limit=LONG_take_profit, stop=LONG_stop_loss, alert_message = '{"message": "exit_long"}')
Replace the script with:
<?php
file_put_contents("/home/user/public_html/data.txt", print_r([$_GET, $_POST, $_SERVER], true));
to better understand the incoming data.
Maybe the data are present in $_POST variable, if not, post the whole result here (via pastebin).
(also make sure the PHP script starts with <?php)

Difficulty receiving Json Form-Data Through PostMan

While receiving data on PHP file code is like -
print_r($_POST);
echo $name = $_REQUEST['name'];
I am getting null array
How to get the value while posting ? Here is the headers I used
use x-www-form-urlencoded while posting data.Then
echo json_encode($_POST);//prints into json format
Try it will works.
NOTE: By default, the $http service will transform the outgoing request by serializing the data as JSON and then posting it with the content- type, "application/json". When we want to post the value as a FORM post, we need to change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded".

Can not send POST variables to php script on localhost using Postman

I am developing the client side of a web application in iOS/Swift, and right now I am testing the part that communicates with the server. I setup a basic website on localhost at:
http://localhost/~username/ConnectivityTest/login
(which corresponds to /Users/username/Sites/ConnectivityTest/login on my Mac's file system).
The server side script (index.php on the directory above) is:
<?PHP
$userId = $_POST["userId"];
$password = $_POST["password"];
if (empty($userId) || empty($password)){
echo "Error: empty post variables";
}
else{
// Process credentials...
I am using the NSURLSession API on iOS, but I noticed that no matter how I configure my requests, even though the connection succeeds (i.e., returns an http code of 200 and the response body as data), the POST variables are unavailable (empty) on the server side.
So I decided to try sending the request manually using Postman on the browser (to try to rule out any mistakes on my iOS/Swift code), but I don't know how I should configure it (I am not versed in HTTP, it all is still a bit confusing to me):
Should I set the Content-Type header to application/json, application/x-www-form-urlencoded, or what?
Should I send the body data as form-data, x-www-form-urlencoded or raw?
In Postman, I set the body data (raw) as follows:
{
"userId":"my-user-name",
"password":"123456"
}
Alternativley, as form-data, it is:
userId my-user-name [Text]
password 12345 [Text]
As x-www-form-urlencoded, it is:
userId my-user-name
password 12345
Everything I try gives me the response "Error: empty post variables" that I set in my code's error path (i.e., $_POST['userId'] or $_POST['password'] are empty).
If, instead, I pass the variables as URL parameters:
http://localhost/~username/ConnectivityTest/login/index.php?userId=my-user-name&password=12345
...and access them in the script as &_GET['userId'] and $_GET['password'], it works fine.
what am I missing?
UPDATE: I created an HTML file in the same directory as the php file:
<html>
<body>
<form action="index.php" method="post">
User name: <input type="text" name="userId"><br>
Password: <input type="text" name="password"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
If I load the above page in a browser, fill in the fields and submit the form, the $_POST variables on my php script get the correct values. So the php code is correct, and I am setting up my request wrong in Postman (still don't know why).
UPDATE 2: Just in case there was a problem with localhost, I moved the script to a shared wb hosting service that I control, but the result is the same.
UPDATE 3: I must have missed it somehow before, but there is ONE setup that I got working:
Headers: Content-Type application/x-www-form-urlencoded
Body ("raw"): userId=my-user-name&password=123456
However, this restricts me to flat lists of key/value; If I wish to send more structured (i.e., nested) data to the server I need JSON support...
After searching here and there, I discovered that the post body data gets into the $_POST variables only when you send them as a form -i.e., application/x-www-form-urlencoded- (I guess that is what $_POST stands for, not the method used for the request). Correct me if I'm saying something that isn't correct.
When using a Content-Type of application/json, code like the following does the trick:
$data = json_decode(file_get_contents('php://input'), true);
$userId = $data["userId"];
$password = $data["password"];
I guess this is very basic stuff, but then again, my knowledge of HTTP is very limited...
A mistake I made when first using Postman was setting the params when using the POST method which would fail. I tried your Update 3 which worked and then I realized there were key value pairs in the Body tab.
Removing the params, setting the Body to "x-www-form-urlencoded" and adding the variables to be posted here works as expected.
My oversight was I figured there would be a single section to enter the values and the method would determine how to pass them along which makes sense in case you would like to send some parameters in the URL with the POST
Comment by #FirstOne saved me. I added a forward slash to the URL and it solved the problem. This way, my php script could detect the request as POST even without setting header to
Content-Type application/x-www-form-
urlencoded
I also tested my code without a header and it works fine. I tested with Content-type: application/json too and it works fine.
if($_SERVER['REQUEST_METHOD] = 'POST') { echo 'Request is post'; }
My script returned 'Request is post' using RESTEasy - Rest client on Chrome.
Thanks, FirstOne.

Can't read raw POST body data - how to do this in this example?

I'm setting an API for my server for another developer. I'm currently using Flash AIR to send POST data to my server, and simply extract the variables as in
$command = $_POST['command'].
However, he's not using Flash, and is sending data like so:
https://www.mysite.com POST /api/account.php?command=login HTTP/1.1
Content-Type: application/json
Connection: close
command=login
params {"pass":"12345678","token":"","appID":"theirApp","user":"johnnyb","ver":"2.0","Library_ID":"1"}
My server is returning him an error saying that the 'command' parameter is missing.
What do I need to do my end to extract the $_POST var 'command' from his above data?
I've tried file_get_contents('php://input') and http_get_request_body(), but although they don't error, they don't show anything.
Thanks for your help.
The request claims that it is sending JSON.
Content-Type: application/json
However, this:
command=login
params {"pass":"12345678","token":"","appID":"theirApp","user":"johnnyb","ver":"2.0","Library_ID":"1"}
… is not JSON.
If you get rid of everything before the { then it would be JSON and you should be able to read it with file_get_contents('php://input') (and could then pass it through a decoder.
I've tried file_get_contents('php://input') and http_get_request_body() … they don't show anything.
They should work.
When I print out file_get_contents('php://input') for the comms … I get command=login, yet...
I thought you said you didn't get anything
if(!isset($_POST['command']))
$_POST will only be populated for the two standard HTML form encoding methods. If you are using JSON then it won't be automatically parsed, you have to do it yourself (with valid JSON input (so the additional data would need to be encoded in the JSON text with the rest of the data)), file_get_contents('php://input') and decode_json).
"Content-Type should be www-form-urlencoded" from #Cole (correct answer)
More info here: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1
The command parameter needs to be part of the data, and the whole thing should be valid JSON. As is, command=login, it is not valid JSON.
Add it to the params object or make a containing object, like
{
command:'login',
params :{"pass":"12345678","token":"","appID":"theirApp","user":"johnnyb","ver":"2.0","Library_ID":"1"}
}

XHR request to PHP

Hi i am having problems with an XHR post request.
in javascript:
self.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
self.xhr.setRequestHeader("Method", "POST " + url + " HTTP/1.1");
In firebug:
Parametersapplication/x-www-form-urlencoded
{"u":"andrepadez","m":"\n...
JSON
m
"sfdsfsdfdsfdsf"
u
"andrepadez"
Source
{"u":"andrepadez","m":"\nsfdsfsdfdsfdsf"}
In .NET, I post this to an .ASHX, and in the ProcessRequest i do:
StreamReader sr = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding);
javaScriptSerializer.Deserialize<MyClass>(message);
and I have no problems.
I don't know how to get the data in PHP, either $_POST and $_REQUEST are empty arrays.
Any help please?
thanks
You've not set a field name for the data being sent. PHP requires data coming in via POST to be in a fieldname=value format. _POST is an array like any other, and every value stored in a PHP array must have a key (which is the form field name).
You can try retrieving the data by reading from php://input:
$post_data = file_get_contents('php://input');
But the simplest solution is to provide a fieldname in your XHR call.
You are setting the Content-Type to application/x-www-form-urlencoded, but you are setting the content to json. I'm guessing this is confusing your PHP webserver. Try setting your POST contents to what you tell the server it will be (application/x-www-form-urlencoded) or read the raw HTTP contents in php://input.
If you set the Content-Type to application/x-www-form-urlencoded then naturally PHP will want to parse the POST body. But as the data does not actually constitute form data, it is discarded as invalid.
You need to set the correct CT application/json (actually doesn't matter) so PHP will leave it alone. Then it becomes available as php://input or $HTTP_RAW_POST_DATA

Categories