PHP script to use for HTTP post request - php

Hope someone could spare time to help a rookie. I have to set up my server and then provide a supplier with the URL of the page which has to be able to receive a HTTP-Post request like the following - For each post received, your page will have to answer with a "+OK", in order to confirm the correct delivery of the notification.
POST /yourpage.php HTTP/1.1
Host: www.yoursite.com
Content-Length: 215
Connection: Keep-Alive
Content-type: application/x-www-form-urlencoded
Accept-Language: it
Cache-Control: no-cache
destination=%2B40757732753&text=sms+test+example&originator=%2B391234567890&date_time=20160606074445
What would be the best way to go about this instruction? I have some basic knowledge of PHP (still learning), so we can use PHP.
Thanks in advance
Marinda

You need learn about global variables in PHP, php has $_POST able to get content sended on body of post and do something with it.
<?php
// this will create a variable with data of destination sent
$destination = $_POST['destination']
...
// just print +OK
echo "+OK"
But if you want send SMS to Mobile, you need use services to send for you, in general has a cost for this and able to send a limited number of SMSs depend your plan.
I hope it help you

Check $_POST variable. It's a kind of special variable for this language. Then, you can:
<?php
$isOK = true;
// Check if POST parameter destination is set and it is not blank, you
// can repeat this validation with all your parameters, changing
// destination by its name.
if (!isset($_POST['destination']) || trim($_POST['destination']) == '') {
$isOK = false;
}
if ($isOK) {
echo "+OK";
}

Related

Issue with google calendar push notification

I tried implementing the google calendar push notification in my server.
Using the outhplayground, i was able to successfully subscribe to the service.
I am getting notifications to my registered url when a change takes place in the calendar.
The only issue is that the response that i receive doesnt have data. Its an empty response.
Could anyone tell me what the issue would be. I am using PHP code in the backend to access the request hitting my url.
authplayground code:
POST /calendar/v3/calendars/calendarname#gmail.com/events/watch HTTP/1.1
Host: www.googleapis.com
Content-length: 161
Content-type: application/json
Authorization: Bearer access_token
{
"id": "01234267-89a6-cdef-0123456789ab", // Your channel ID.
"type": "web_hook",
"address": "https://example.com/response" // Your receiving URL.
}
Code to accept request:
$json = file_get_contents('php://input');
$request = json_decode($json, true);
$post_request = $_POST;
$get_request = $_REQUEST;
As I was getting an empty response, i tried writing the code to accept any possible way.
Google sends the response in the headers as an array.
Try this:
$response = apache_request_headers();
if($response) {
print_r($response);
}else {
echo 'The apache_request_headers() did not find any headers.'; //Or google is not sending any.
}
You may also try:
getallheaders()
if the apache_request_headers did not work.
Testing this can be difficult. You may want to set up a log that sends any data your page gets to a table on your database so that you can go back and inspect to see what type of progress you are making.
You can get the values like this:
$channelId = $_SERVER['HTTP_X_GOOG_CHANNEL_ID'];
$resourceId = $_SERVER['HTTP_X_GOOG_RESOURCE_ID'];
if($channelId) {
file_put_contents('webhook.txt', $channelId.' ||| '.$resourceId);
}
You can get the different headers here: https://developers.google.com/calendar/v3/push#understanding-the-notification-message-format

PHP response to HEAD request

I have a PHP script that serves portions of a PDF file by byte ranges.
If an HTTP HEAD request is received, it should send back headers (including the PDF file size) but not the actual file contents. I have tried this:
header('HTTP/1.1 200 OK');
header('Content-Type: application/pdf');
header('Accept-Ranges: bytes');
header('Content-Length: '.filesize($Pathname));
die;
The problem is that something (I assume the web server == LiteSpeed) replaces the Content-Length header with Content-Length: 0 - which defeats the whole purpose.
Can anyone suggest what I should be doing? Thanks
From w3c Hypertext Transfer Protocol -- HTTP/1.1:
When a Content-Length is given in a message where a message-body is
allowed, its field value MUST exactly match the number of OCTETs in
the message-body. HTTP/1.1 user agents MUST notify the user when an
invalid length is received and detected.
And:
The Content-Length entity-header field indicates the size of the
entity-body, in decimal number of OCTETs, sent to the recipient or, in
the case of the HEAD method, the size of the entity-body that would
have been sent had the request been a GET.
So, I suppose, your code will properly work if you send real HEAD request to your server.
It's the webserver job, not yours.
In my case I left everything to the Apache webserver and nothing changed in my php code except of how the requests is being parsed
For example things like
if($_SERVER['REQUEST_METHOD'] === "GET"){
//ok
}else{
//send 400 Bad Request
}
are changed to
if($_SERVER['REQUEST_METHOD'] === "GET" || $_SERVER['REQUEST_METHOD'] === "HEAD"){
//ok
}else{
//send 400 Bad Request
}
and Apache did all the heavy lifting (striped the response body).
(don't try to ob_clean() or die("") or things like this).
related resources:
http://hc.apache.org/httpclient-3.x/methods/head.html
https://security.stackexchange.com/questions/62811/should-i-disable-http-head-requests
Apache 2.2.2 response on HEAD requests
As Lurii mentioned, the content length is affected by your request type.
With GET requests, a non-matching content length may result in a hanging client, so LiteSpeed will verify the content length before sending the header to the client.
Using a HEAD request should return the content length as expected.

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.

PHP HTTP Post Server - can't get post requests

So I'm working on a group project for school, and we're working with a client who wants a companion app of sorts to go with his companies device. We provide the device a host IP or domain and it sends HTTP Post requests in the form of XML every 5 seconds or so. The problem we're having is we have NO idea how to capture the data being sent on our server. Simply trying to grab and dump all $_POST data yields an empty array, and our attempts to use a socket have produced similar results.
We've tried pointing the device to http://posttestserver.com/ - and it gets the data perfectly, though there is no source code available to see how the site operates. Admittedly our knowledge of server side scripting is limited at best as we've only been working with PHP for a couple months, and this isn't something that has been covered.
The above mentioned post server produces the following output ( with some omitted data for privacy ). Any help in reproducing this or simply assistance in getting the data on our server would be greatly appreciated!
Time: Sun, 09 Nov 14 14:20:26 -0800
Source ip: ######
Headers (Some may be inserted by server)
HTTP_CONNECTION = close
REQUEST_URI = /post.php
QUERY_STRING =
REQUEST_METHOD = POST
GATEWAY_INTERFACE = CGI/1.1
REMOTE_PORT = ######
REMOTE_ADDR = ######
CONTENT_LENGTH = 488
CONTENT_TYPE = application/xml
HTTP_USER_AGENT = Raven Uploader/v1
HTTP_FROM = ######
HTTP_ACCEPT = */*
HTTP_HOST = posttestserver.com
HTTPS = on
UNIQUE_ID = VF-oqtBx6hIAACKZ7j0AAAAH
REQUEST_TIME_FLOAT = 1415571626.7993
REQUEST_TIME = 1415571626
No Post Params.
== Begin post body ==
<?xml version="1.0"?><clientcompany macId="######" version="1.1" timestamp="1415571625s">
<PriceCluster>
<DeviceMacId>######</DeviceMacId>
<MeterMacId>######</MeterMacId>
<TimeStamp>0x1bf2a52d</TimeStamp>
<Price>0x00000467</Price>
<Currency>0x007c</Currency>
<TrailingDigits>0x04</TrailingDigits>
<Tier>0x01</Tier>
<StartTime>0x1bf2a52d</StartTime>
<Duration>0xffff</Duration>
<RateLabel>Block 2</RateLabel>
</PriceCluster>
</clientcompany>
== End post body ==
Upload contains PUT data:
<?xml version="1.0"?><clientcompany macId="0xd8d5b90016d1" version="1.1" timestamp="1415571625s">
<PriceCluster>
<DeviceMacId>######</DeviceMacId>
<MeterMacId>######</MeterMacId>
<TimeStamp>0x1bf2a52d</TimeStamp>
<Price>0x00000467</Price>
<Currency>0x007c</Currency>
<TrailingDigits>0x04</TrailingDigits>
<Tier>0x01</Tier>
<StartTime>0x1bf2a52d</StartTime>
<Duration>0xffff</Duration>
<RateLabel>Block 2</RateLabel>
</PriceCluster>
</clientcompany>
You need to capture the raw input stream:
//$data = $_POST; <-- will be empty unless you are sending a key value pair(s)
$data = file_get_contents('php://input'); //<-- will capture all posted data
echo '== Begin post body ==';
echo $data;
echo '== End post body ==';
If you need to see headers as well you can use getallheaders function: http://php.net/manual/en/function.getallheaders.php
instead of $_POST check $HTTP_RAW_POST_DATA var

How to push notification from rest client for testing purpose

Hi I am trying to push the notification from rest client to android app. I am doing like below -
URL - https://android.googleapis.com/gcm/send
Method - POST
Headers - Authorization: my_server_key
I always get this message
Status Code: 401 Unauthorized
Alternate-Protocol: 443:quic,p=0.002
Cache-Control: private, max-age=0
I am not sure what I am missing & last I am using correct server api key.
Please assist & thanks in advance.
Push notification uses Web Socket. You cannot do this using HTTP protocol unless you have a server side implementation set up to respond to your request through Web Socket.
I set this values in the header then it is working fine for me.
Below is the header key & value.
A) Authorization: & it value likes key=API_KEY
B) Content-Type: application/json
I hope you are done with your request but it will help to others
You have to send like this
In head
-------
Headder Value
Authorization key=your value
Content-Type application/json
In Body
-------
Something like this
{
"registration_ids" : ["Your id"],
"data" : {
"message":"Your message"
}
}
Hope it will help

Categories