How to receive in php a post sent with RestSharp - php

I need to receive in PHP an http post from RestSharp / 105.2.3.0, supposedly send me the following:
POST / api / Msg HTTP / 1.1
Accept: application / json
Authorization: Basic K9ykc3QyOmlmZWlnb2hjaGFpZ2hpZWxpaH53
User-Agent: RestSharp / 105.2.3.0
Content-Type: application / json
Host: xxx.xxx.xxx.xxx
Content-Length: 80
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
{"Name": "Bear", "LastName": "Lukas", "time": 797, "option": 1}
I tried to use the following code in php but it did not work, any ideas?
<?php
$json_params=file_get_contents("php://input");
$decoded_params = json_decode($json_params,true);
foreach ($decoded_params as $dp){
echo $dp;
}

Related

POST Empty Regardless of Request [duplicate]

This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 1 year ago.
I am using jQuery to submit the following request:
$.ajax({
url: encodeURI('/server/api/user/update.php/'),
method: 'POST',
contentType: 'application/json',
headers: {
'Authorization': 'Bearer ' + utility.getJsonWebToken()
},
data: JSON.stringify(e.model),
dataType: 'json'
})
And I have the following PHP code that verifies that the request is valid and contains the necessary body:
// check for bad method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
$returnedJson['error'] = 'The supplied request method is not supported for the requested resource. This resource expects a POST request.';
echo json_encode($returnedJson);
return;
}
// check for bad request
$errors = array();
$user = new UserModel();
foreach (UserModel::$RequiredColumnNames as $property) {
$success = ControllerUtility::isValueInRequest($_POST, $property);
if (!$success) {
array_push($errors, $property);
continue;
}
$user->$property = $_POST[$property];
}
if (count($errors) > 0) {
http_response_code(400);
$returnedJson['error'] = 'Malformed request syntax. The following properties are missing from the request: ' . join(', ', $errors);
echo json_encode($returnedJson);
return;
}
Every time I submit the request, I get 400 error with the 'Malformed request syntax. The following properties are missing from the request: ...' error message.
I echoed the $_POST and $_REQUEST but in both instances and empty array is returned.
I verified that the request headers is a POST:
POST /server/api/user/update.php/ HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json
Authorization: Bearer -removed-
X-Requested-With: XMLHttpRequest
Content-Length: 180
Origin: http://localhost
Connection: keep-alive
Referer: -removed-
Sec-GPC: 1
And the fields are included in my request JSON:
{
"CreatedBy": null,
"CreatedOn": "2021-02-28 13:53:54",
"DeletedOn": null,
"Email": "-removed-",
"ModifiedBy": "1",
"ModifiedOn": "2021-02-28 16:35:51",
"UserId": "1",
"Username": "Adminn"
}
I have even removed the content-type header from my PHP without success. I've also tried just passing e.model instead of calling stringify in the AJAX request. At this point I'm at a loss as to what I'm doing wrong.
// echo the json string from php://input.
file_get_contents('php://input');

ipinfo.io via PHP's file_get_contents() and cURL fail

I try to get a GeoLocation data from http://ipinfo.io,
Here is my way :
$resp = file_get_contents('http://ipinfo.io/json');
$data = json_decode($resp);
It return an error :
Warning: file_get_contents(http://ipinfo.io/json): failed to open stream: Permission denied in ....
But then I access the link (http://ipinfo.io/json) manually in the URL box of my browser, it shows a correct json.
I also try it with cURL :
$curlSession = curl_init();
curl_setopt($curlSession, CURLOPT_URL, "ipinfo.io/json");
curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($curlSession);
if (FALSE === $resp) {
echo curl_errno($curlSession);
}
curl_close($curlSession);
It echo a number of 7, and i look up in the internet, error 7 means Couldn't connect to the server.
Any idea why ?
Thank you
I run http://ipinfo.io, and we don't block access to any IPs (we do rate limit requests from IPs, but that'd result in a HTTP status code, not a blocked connection). This sounds like a config issue with your server to me. Some hosts lock down file_get_contents so it can't open URLs, or might have blocked http://ipinfo.io. Are few ways to track this down:
1) Can you open another URL with file_get_contents? Eg. what happens when you file_get_contents('http://google.com'). If you get a permission denied error there then you should speak to your hosting provider
2) Does command line curl work for ipinfo.io? The -i -v flags should give you more information about what's going on here. Here's what a successful request looks like:
$ curl -iv ipinfo.io
* Rebuilt URL to: ipinfo.io/
* Trying 54.68.119.255...
* Connected to ipinfo.io (54.68.119.255) port 80 (#0)
> GET / HTTP/1.1
> Host: ipinfo.io
> User-Agent: curl/7.49.1
> Accept: */*
>
< HTTP/1.1 200 OK
HTTP/1.1 200 OK
< Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: *
< Content-Type: application/json; charset=utf-8
Content-Type: application/json; charset=utf-8
< Date: Sun, 15 Jan 2017 18:38:44 GMT
Date: Sun, 15 Jan 2017 18:38:44 GMT
< Server: nginx/1.8.1
Server: nginx/1.8.1
< Set-Cookie: first_referrer=; Path=/
Set-Cookie: first_referrer=; Path=/
< X-Content-Type-Options: nosniff
X-Content-Type-Options: nosniff
< Content-Length: 252
Content-Length: 252
< Connection: keep-alive
Connection: keep-alive
<
{
"ip": "24.6.61.239",
"hostname": "c-24-6-61-239.hsd1.ca.comcast.net",
"city": "Mountain View",
"region": "California",
"country": "US",
"loc": "37.3845,-122.0881",
"org": "AS7922 Comcast Cable Communications, LLC",
"postal": "94040"
* Connection #0 to host ipinfo.io left intact
}
Quite often a server will be configured to prevent requests where there is no User-Agent string present in the request headers so you can add a context argument to file_get_contents that supplies a User-Agent and any other headers you need.
$args=array(
'http'=>array(
'method' => "GET",
'header' => implode( "\n", array(
'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Host: ipinfo.io'
)
)
)
);
/* create the context */
$context=stream_context_create( $args );
$resp = file_get_contents( 'http://ipinfo.io/json', FILE_TEXT, $context );
$data = json_decode( $resp );
echo '<pre>',print_r( $data,true ),'</pre>';
i see 2 plausible explanations here.
1: you use a shitty DNS server. try GoogleDNS (8.8.8.8) instead.
curl_setopt($curlSession,CURLOPT_DNS_LOCAL_IP4,'8.8.8.8');
if that fixes it, contact your DNS provider and sort it out with them
2: you're IP banned. try to just create a TCP socket to their ip, see if you can do that.
<?php
$sock=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
var_dump($sock,socket_connect($sock,gethostbyname('ipinfo.io'),80),socket_close($sock));
if you can't do that, you're probably IP banned

Read POST webhook PHP

I'm trying to read the contents of a webhook notification in php. The content of the request is in the link below:
Link POST
HEADERS:
Pragma: no-cache
X-Request-Id: fec7f2ea-ae08-4fc1-9f81-b7ed9b976100
X-Newrelic-Transaction: PxQDWVNWCgBWBlJWVldRV1dUFB8EBw8RVU4aVgANAQAAA1tSBQBVBFUFUkNKQQtVVlNTUVZQFTs=
Accept: text/html, image/gif, image/jpeg, *; q=.2, /; q=.2
Connect-Time: 2
Connection: close
Content-Length: 931
Cache-Control: no-cache
User-Agent: Java/1.7.0_72
Accept-Encoding: gzip
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Via: 1.1 vegur
X-Newrelic-Id: UgcDUFdVGwQAXFdRBAU=
Host: requestb.in
Total-Route-Time: 0
FORM/POST PARAMETERS:
data: { "event": "PAYMENT_UPDATED", "payment": { "object": "payment", "id": "pay_158657847699", "customer": "cus_artujit2nfYe", "value": 160.0, "netValue": 155.75, "originalValue": null, "nossoNumero": "34271724", "description": "", "billingType": "BOLETO", "status": "PENDING", "dueDate": "21/12/2016", "paymentDate": null, "invoiceUrl": "", "boletoUrl": "", "invoiceNumber": "00507815", "externalReference": null, "deleted": false } }
I tried unsuccessfully through the line code: $datasrc = $_POST;
I also tried to read with $ _REQUEST unsuccessfully.
How to read the content in php?
No clue what webhook is or does. But if it is sent as as POST request to a page in PHP, the data posted will be present in the $_POST array.
To see what's in it: var_dump($_POST); will show you the array and it's structure.
To get the value of a specific key: $variable = $_POST['key']; will do the trick.
If I interpret the stuff you posted correctly the json encoded content should be in $_POST['data']; .
To decode the json encoded string, PHP has helpful functions such as json_decode.
$data=json_decode($_POST['data'], true); should give you a PHP array with the data.

Guzzle curl request getting empty response body but status is 200 and Content-Length header is correct

I am making a request through Guzzle 3.8.1 for a Jasper report (via the Jasper Server API) that is over 2MB and I'm getting a response with the correct Content-Length header but no response body.
Guzzle request:
GET /jasperserver/rest_v2/reports/projects/i3app_suite/Resource/BulkShiftExport.csv?ACCOUNT_ID=2&START_DATETIME=2015-01-01&END_DATETIME=2015-01-31 HTTP/1.1
Host: jasper.i3app:8080
User-Agent: Guzzle/3.8.1 curl/7.19.7 PHP/5.5.8
Authorization: Basic ***=
Response:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Cache-Control: private
Expires: Wed, 31 Dec 1969 17:00:00 MST
P3P: CP="ALL"
Set-Cookie: JSESSIONID=F0B0F72B65A8145B45DA9DB2BACE53D8; Path=/jasperserver/; HttpOnly, userLocale=en_US;Expires=Fri, 13-Feb-2015 18:56:44 GMT;HttpOnly
Content-Disposition: attachment; filename="BulkShiftExport.csv"
output-final: true
Content-Type: application/vnd.ms-excel
Content-Length: 2173897
Date: Thu, 12 Feb 2015 18:57:02 GMT
If I make this request through curl on the command line (or request it in a browser) I get the report as expected
GET /jasperserver/rest_v2/reports/projects/i3app_suite/Resource/BulkShiftExport.csv?ACCOUNT_ID=2&START_DATETIME=2015-01-01&END_DATETIME=2015-01-30 HTTP/1.1
Authorization: Basic ***=
User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.15.3 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
Host: jasper.i3app:8080
Accept: */*
< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< Cache-Control: private
< Expires: Wed, 31 Dec 1969 17:00:00 MST
< P3P: CP="ALL"
< Set-Cookie: JSESSIONID=AF1BF885354AF3E352DD9E18FA044A4B; Path=/jasperserver/; HttpOnly
< Set-Cookie: userLocale=en_US;Expires=Fri, 13-Feb-2015 19:03:42 GMT;HttpOnly
< Content-Disposition: attachment; filename="BulkShiftExport.csv"
< output-final: true
< Content-Type: application/vnd.ms-excel
< Content-Length: 2113902
< Date: Thu, 12 Feb 2015 19:03:49 GMT
<
{ [data not shown]
The only difference I could see was Accept: */* in the curl request. I tried adding that header to the guzzle request and got the same result.
When making the request through the Guzzle client it appears to take the same amount of time (5-6 seconds) to receive the response, and it sets the Content-Length header, but the response body is empty. Why am I getting an empty response body though Guzzle which is using curl but not when using curl on the command line? Is there an option I need to set to make this work?
$request = $this->getGuzzleClient()->createRequest('GET');
$config = $this->getConfig();
$url = new Url(
$config['scheme'],
$config['host'],
$config['user'],
$config['pass'],
$config['port'],
$config['path'] . $reportPath . '.' . $format,
new QueryString($parameters)
);
$request->setUrl($url);
$response = $request->send();
...
public function getGuzzleClient()
{
if (!$this->restClient) {
$client = new GuzzleClient();
$this->setRestClient($client);
}
return $this->restClient;
}
In my case, I was using MockHandler mistakenly.

PHP code doesnt "compile" when connecting via sockets

I am writing a script for mIRC that will fetch data from my webserver, that code is generated via PHP.
It works just fine when i connect via my browser (firefox).
However, when i connect via the mIRC sockets, server fails to "compile" my PHP code. I can still able to fetch any other text or html. Seems like the webserver (litespeed) does not acknowledge my http requests(?!)
This is my header information that I pass to the server:
sockwrite -n ccsw_sock_reg GET /ccsw/ccsw.php?action=register&username= $+ %ccsw_username_temp $+ &password= $+ %ccsw_username_temp HTTP/1.1
sockwrite -n ccsw_sock_reg Host: www.[HIDDEN].com
sockwrite -n ccsw_sock_reg Connection: close
sockwrite -n ccsw_sock_reg User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9) Gecko/2008052906 Firefox/3.0
sockwrite -n ccsw_sock_reg Accept-Encoding: gzip
sockwrite -n ccsw_sock_reg Accept:Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
sockwrite -n ccsw_sock_reg Accept-Language: en-us,en;q=0.5
sockwrite -n ccsw_sock_reg Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7
;sockwrite -n ccsw_sock_reg Cache-Control: no-cache
sockwrite -n ccsw_sock_reg Cache-Control: no-store, no-cache, must-revalidate
sockwrite -n ccsw_sock_reg Cache-Control: post-check=0, pre-check=0
sockwrite -n ccsw_sock_reg Pragma: no-cache
sockwrite -n ccsw_sock_reg $crlf
I've tried using a apache server instead of litespeed, but it doesn't solve either. I still don't get any PHP generated code to show.
Am i missing some headers? Should I do it in a completely different way?
update:
mIRC code:
alias testsock {
sockclose testsock
sockopen testsock www.[HIDDEN].com 80
}
on *:sockopen:testsock: {
sockwrite -nt testsock GET /ccsw/ccsw.php?action=register&username= $+ %ccsw_username_temp $+ &password= $+ %ccsw_username_temp HTTP/1.0
sockwrite -nt testsock Host: www.[HIDDEN].com
sockwrite -nt testsock $crlf
}
on *:sockread:testsock: {
%ccsw_content_start = 0
if ($sockerr > 0) return
sockread %temp
while ($sockbr) {
echo response: %temp
sockread %temp
}
}
response:
reponse: HTTP/1.0 200 OK
reponse: Date: Thu, 02 May 2013 14:45:07 GMT
reponse: Server: LiteSpeed
reponse: Connection: close
reponse: X-Powered-By: PHP/5.2.17
reponse: Content-Type: text/html
reponse: Content-Length: 43
reponse:
and after that last "reponse: " i should get a php generated line with "reponse: true"
the "reponse: " is just a prefix for my echo..
If you look carefully you will see the following response header
"Content-Length: 43"
That means you are getting response and the problem lies inside your SOCKREAD event.
Try this following code:
on *:sockread:testsock: {
if ($sockerr) {
return
}
var %line
:start
sockread %line
if (%line) {
echo -ag SOCKREAD: %line
}
if ($sockbr) {
goto start
}
}

Categories