Javascript + PHP $_POST array empty - php

While trying to send a POST request via xmlhttp.open("POST", "url", true) (javascript) to the server I get an empty $_POST array.
Firebug shows that the data is being sent. Here is the data string from Firebug: a=1&q=151a45a150.... But $_POST['q'] returns nothing.
The interesting thing is that file_get_contents('php://input') does have my data (the string above), but PHP somehow doesn't recognize it. Tried both $_POST and $_REQUEST, nothing works.
Headers being sent:
POST /test.php HTTP/1.1
Host: website.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://website.com/
Content-Length: 156
Content-Type: text/plain; charset=UTF-8
Pragma: no-cache
Cache-Control: no-cache
Thank you for any suggestions.

It looks like you're missing the correct Content-Type header. This is necessary for POST requests:
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

Send a
Content-Type: application/x-www-form-urlencoded
header instead of text/plain

You have to write it like this:
xmlhttp.open("POST", "script.php", true);
xmlhttp.send("foo=bar&answer=42");

Just spent hours trying to find a fix for this very problem.
I made the idiotic mistake of concatenating several strings which I wanted to be the parameters, and THEN calling encodeURIComponent on the whole lot. This of course meant that
foo=bar&this=that
became
foo%3Dbar%26this%3Dthat
which of course is gibberish to a PHP script. While I doubt there can be many people who would do something as silly as this, I hope it saves someone the headache I just gave myself....

Related

PayPal sandbox IPN validation always return INVALID

I googled this question and tried all suggestions but nothing works.
I tried this code: https://developer.paypal.com/docs/classic/ipn/ht_ipn/ but it don't work. Just copy-pasted it and deleted old magick_quotes routunes.
I tried this code: http://samples.geekality.net/view-source.php?file=ipn/ipn_handler.class.php and it also do not work.
In all cases I tried to do following:
$req = 'cmd=_notify-validate&' . file_get_contents('php://input');
To ensure I sent to IPN exactly what it sent to me. In addition I used the debug proxy (Fiddler) and saved what IPN sent to me and what I sent to IPN. The requests bodies are byte-to-byte identical except my request is prefixed by the cmd=_notify-validate& string.
Yes, I checked I use proper sandbox URL. Here are entire requests bodies:
What IPN sent to me: (I just replaced personal data to XXX)
POST http://localhost.loc/en/payment/success/1 HTTP/1.1
Host: localhost.loc
Connection: keep-alive
Content-Length: 921
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4
mc_gross=1.00&protection_eligibility=Ineligible&payer_id=5XNKM66NSDKC4&tax=0.00&payment_date=05%3A34%3A11+Jun+01%2C+2015+PDT&payment_status=Completed&charset=utf-8&first_name=XXX&mc_fee=0.33&notify_version=3.8&custom=topup%3A262262%3A1%3A1433162020&payer_status=verified&business=XXX&quantity=1&payer_email=XXX&verify_sign=AG58dBsn5g2z8O8NEjotbuJGP14PAIpZ4k26VL8IyhaDPkcDRj002Keq&memo=hmgvjgjhgfjhfggjhfjtfgjh&txn_id=4CN141026K278934Y&payment_type=instant&last_name=XXX&receiver_email=XXX&payment_fee=0.33&receiver_id=DCMXPXGX4QX6J&txn_type=web_accept&item_name=Account+top+up&mc_currency=USD&item_number=Account+262262+top+up&residence_country=US&test_ipn=1&handling_amount=0.00&transaction_subject=topup%3A262262%3A1%3A1433162020&payment_gross=1.00&shipping=0.00&auth=ANSTBwT3znll-gJQZO2cLoV5QJFW9v8W.FqyWxffdtI0L-9mfsoe2xRL44M86Sn2XtYGtcqG4Fjjel1kdYZyxpQ
What I sent to IPN:
POST https://www.sandbox.paypal.com/cgi-bin/webscr HTTP/1.1
Host: www.sandbox.paypal.com
Accept: */*
Content-Length: 942
Content-Type: application/x-www-form-urlencoded
cmd=_notify-validate&mc_gross=1.00&protection_eligibility=Ineligible&payer_id=5XNKM66NSDKC4&tax=0.00&payment_date=05%3A34%3A11+Jun+01%2C+2015+PDT&payment_status=Completed&charset=utf-8&first_name=XXX&mc_fee=0.33&notify_version=3.8&custom=topup%3A262262%3A1%3A1433162020&payer_status=verified&business=XXX&quantity=1&payer_email=XXX&verify_sign=AG58dBsn5g2z8O8NEjotbuJGP14PAIpZ4k26VL8IyhaDPkcDRj002Keq&memo=hmgvjgjhgfjhfggjhfjtfgjh&txn_id=4CN141026K278934Y&payment_type=instant&last_name=XXX&receiver_email=XXX&payment_fee=0.33&receiver_id=DCMXPXGX4QX6J&txn_type=web_accept&item_name=Account+top+up&mc_currency=USD&item_number=Account+262262+top+up&residence_country=US&test_ipn=1&handling_amount=0.00&transaction_subject=topup%3A262262%3A1%3A1433162020&payment_gross=1.00&shipping=0.00&auth=ANSTBwT3znll-gJQZO2cLoV5QJFW9v8W.FqyWxffdtI0L-9mfsoe2xRL44M86Sn2XtYGtcqG4Fjjel1kdYZyxpQ
Can anyone help me what I do wrong?
Thanks.
AARRRRGH!!!!!!!! I have only dirty words to PayPal!!!!!!! The problem was in... (drumroll... tadam!) in the charset field! No, its value must be the same as IPN sent it to you, but... in UPPERCASE! IPN sends it in lowercase! So you MUST modify IPN data to verify it successfully regardless manual tells us to return data back "as-is". PayPal bug?
So my final working code is: (using HTTP_Request2)
protected function verifyPostData() {
$this->request->setBody('cmd=_notify-validate&' . str_replace('=utf-8', '=UTF-8', file_get_contents('php://input')));
$response = $this->request->send();
if ($response->getStatus() != 200) {
throw new \RuntimeException("Transaction data verification request failed with code {$response->getStatus()}");
}
$content = trim($response->getBody());
return ($content == 'VERIFIED');
}
How I did it: I sent the PDT request for this transaction and obtained transaction data. Then I made field to field comparison of PDT and IPN data. PDT have no some IPN fields such as auth, verify_sign and test_ipn. But all other fields seems must be the same. And the only difference was in the characters case of the charset field. Then I tried to verify modified data and unexpectedly it become successful!
This is a recent PayPal bug, when the customer completes a payment and clicks on "Click here to return.." instead of waiting a few seconds, the parameters passed to the PDT script on your site are sent in lowercase.
This also messes up things like a case-sensitive or encoded cm/custom parameter.
Apparently PayPal are aware of it.

http post request not accepted by php

I am new to php and stackovrflow. So please pardon my initial mistakes.
I am sending post request through extjs4 app. as per Mozilla console Network tab, request is sent. PHP is 5.4.25. Below are the details:
POST /Opp/annt.php HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 83
Origin: http://localhost
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Accept: */*
Referer: http://localhost/opp/index.html?_dc=140
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Form Dataview parsed
aaa=i&bbb=i&ccc=&ddd=&eee=4&fff=5&ggg=&hhh=
PHP file:
header('Content-Type: application/json');
$method = $_SERVER["REQUEST_METHOD"];
$con = new PDO("mysql:host=localhost;dbname=openclass", "root", "") or die("cannot connect to mysql");
$fileContents = file_get_contents("php://input");
echo $fileContents;
json_decode($fileContents, true);
function getPostValue($postData, $fieldName) {
return (!empty($postData[$fieldName]) ? htmlspecialchars($postData[$fieldName]) : NULL);
}
I am not getting any data after post request is executed. Can you pls help in this in pointing out possible issue and solutions
I solved the issue. I was getting error because http post was sending form data in application/x-www-form-urlencoded; charset=UTF-8 formt.
I changed the format sent to json using AJAX requests. This changed the format sent across to json key value pairs.
This helped it read by php.

How to get Rid of the JSON Error in Firefox

My Response Header is
Access-Control-Allow-Meth... GET, POST
Access-Control-Allow-Orig... *
Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection Keep-Alive
Content-Length 81
Content-Type text/html
Date Mon, 26 Aug 2013 06:35:53 GMT
Expires Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive timeout=5, max=99
Pragma no-cache
Server Apache/2.4.3 (Win32) OpenSSL/1.0.1c PHP/5.4.7
X-Powered-By PHP/5.4.7`
And The Request Header is
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Cache-Control no-cache
Connection keep-alive
Content-Length 31
Content-Type application/x-www-form-urlencoded; charset=UTF-8
Cookie USERNAMEEMAIL=shan%40atlos.com; PHPSESSID=8asm46iltcqc9oahsbaaap1c16
Host localhost
Pragma no-cache
Referer http://localhost/test/
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0
X-Requested-With XMLHttpRequest`
i am getting error in firefox "Not Well Formed" what is the problem in this.
i am getting the data correctly in json form but it show also error that is very annoying
Java Script Code to Make Request
GetTopNotification
And Uses a Class for make Ajax Request is
Workspace
Your reponse-header is incorrect.
if(headers_sent()) die('Should not output data before json');
header('Content-type: application/json');
echo json_encode($data_for_json);
exit;
Also, nothing should be sent before the json, and nothing after it either.
In response to comment below:
Somewhere in your php-code you're outputting json. However, as stated, your reponse header is incorrect: the Content-type part should be set to application/json; the above code does just that. A line-by line walktrough:
Checks if you did not already send anything and die if you did
Set the Content-type part of your response header to the appropriate mime-type
Output the json (as it currently is, should be fine)
exit;
More update irt comments
You're creating your json string manually: something i can wholeheartedly advice against, use an array or object and then use json_encode to create you json.
I also added output_buffering over your code, just in case.
Give it a try, new code is here
Update three
In work-space.js Replace this line
self.responseValue = self.getValueFromResponse( jqXHR );
With this
if(type != 'xml') self.responseValue = data;
else self.responseValue = self.getValueFromResponse( jqXHR );
save it, clear the cache, and try again.

Using php curl to fill form on asp.net page

There is a asp.net driven site where I can login and fill a form to place a order after a succesful login. This needs to be done by my server with curl.
Whenever I do this with my browser there is nothing special.
I go to example.com/login.aspx. Fill in fields and post it back. I get a index page back for logged in users. After this i need to click on a link to the form for order placement. Doing this gives me the form, which I fill and send back.This yields the wanted result of an placed order. Analysing the source revealed the page gets submitted through javascript,but the server cannot know how the request is sent if the request is identical. During this process i kept track of all the post requests send from my browser.
Having all the post requests, i wrote some code to do the same with curl.
The algorithm is:
Send a get request to obtain the example.com/login.aspx page
Parse the responds for any hidden fields(as they are used to mimic a statefull connection)
Post the state and the logindata to example.com/login.aspx
Parse the state send back and update it
Get form for order placement
Parse & update the state again
Post the state and the same post data that my browser sent
Print info to file instead of STDERR
During the process cookies are used with curl.
Everything goes smooth until the last POST. Instead of a "Success" or "Failure" result, I get my original form returned to me, with no validation errors mentioned. If I delibarely fill in gibberish or leave some things empty with my browser I get validation errors shown.
I have no experience with asp.net and am completely stuck here, so forgive me if this question is too specific.
Question:
If the headers and post data are exactly the same as from my browser, how can my curl operation have a different result?
For completeness:
POST from browser:
POST /DataEntry.aspx HTTP/1.1
Host: www.iftin.co
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:16.0) Gecko/20100101 Firefox/16.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Language: nl,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Referer: https://www.iftin.co/DataEntry.aspx
Cookie: ASP.NET_SessionId=SomethingX; .hawAuth=SomethingY
Content-Type: application/x-www-form-urlencoded
Content-Length: 10111
Post send by Curl:
POST /DataEntry.aspx HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:16.0) Gecko/20100101 Firefox/16.0
Host: www.iftin.co
Referer: https://www.iftin.co/DataEntry.aspx
Cookie:.hawAuth=SomethingZ; ASP.NET_SessionId=SomethingW
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Language: nl,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 25236
Expect: 100-continue
Content-Type: application/x-www-form-urlencoded;boundary=----------------------------5bb8ec4e5ecc
If people want to see some code, let me know. Thanks for reading and spending time on this.
Ater writing this, I noticed that the Content-Length for my curl request is substantially bigger than for my browsers request. I copied all parameters in the body of the Post of the browser to my code and passed it to curl in a array.
So curl has to add some data to the request by default. Is this the case?
The CURLOPT_SSL_VERIFYPEER is set to false, while the page uses SSL. Could this be it? Why?

save content from header?

I'm looking for help in something that I can't figure out....
I'm receiving in a PHP some data sent by a .swf...
var requestHeader:* = new URLRequestHeader("Content-type", "application/octet-stream");
var request:* = new URLRequest(url);
new URLRequest(url).requestHeaders.push(requestHeader);
request.method = URLRequestMethod.POST;
request.data = this.getByteArray(o, a, l, a2, l2);
navigateToURL(request, "_blank");`
I can't modify that code... that's a swf... but it works...
now... the php i'm using receives this as its header
Host: localhost
Connection: keep-alive
Referer: http://localhost/archivo.swf
Content-Length: 135782
Cache-Control: max-age=0
Origin: null
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16
Content-Type: application/octet-stream
Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Encoding: gzip,deflate,sdch
Accept-Language: es-ES,es;q=0.8,en-US;q=0.6
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
looking at the content-length. I can see that some data was received.
but debugging or printing the PHP. the POST has 0 items. the GET has the session id.
and the REQUEST also has the session id
appending to the header
header("Content-disposition: attachment; filename=archivo.png");
only downloads the content of the printed php (in this case the headers, a 1.something kB file)
is there anyway to retrieve the content that has a size of 135782?
Thanks!
One issue I see is that you should be using a URLLoader to POST data from the SWF, rather than the navigateToURL function.
var urlLoader:URLLoader = new URLLoader();
urlLoader.load(request);
For the Adobe docs:
Note: When using the navigateToURL()
function, the runtime treats a
URLRequest object that uses the POST
method (one that has its method
property set to URLRequestMethod.POST)
as using the GET method.

Categories