Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't read my POST HTTP request's body with PHP !

Tags:

post

php

I've never used PHP but right now, I need to write a PHP file that displays in a log file the content of the body of a POST HTTP request.

I've read that you can access variables of the body via the _POST array. Unfortunately, it seems to be empty, although I'm pretty sure there is stuff in my HTTP request's body !

What should I use to be 100% sure of the content of my HTTP body ?

Thanks.

like image 889
Dirty Henry Avatar asked Jul 29 '10 11:07

Dirty Henry


People also ask

How do I get the body of a POST request?

Getting HTTP POST Body as a String To retrieve the body of the POST request sent to the handler, we'll use the @RequestBody annotation, and assign its value to a String.

What is $_ POST [] in PHP?

PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables. The example below shows a form with an input field and a submit button.

CAN POST request contain body?

POST does require a body, but that body can be an empty document. The difference is subtle, but it's not the same thing.

How do you make a POST API call in PHP?

To make a POST request to an API endpoint, you need to send an HTTP POST request to the server and specify a Content-Type request header that specifies the data media type in the body of the POST request. The Content-Length header indicates the size of the data in the body of the POST request.


2 Answers

$post_body = file_get_contents('php://input');

php://input allows you to read raw POST data. It is a less memory intensive alternative to $HTTP_RAW_POST_DATA and does not need any special php.ini directives. php://input is not available with enctype="multipart/form-data".

(Source: http://php.net/wrappers.php)

like image 96
salathe Avatar answered Sep 18 '22 20:09

salathe


The global variable is $_POST, not _POST. Also it might be that you are sending the data via GET method, in which case you need to use the $_GET global variable.

If you want to check for either POST or GET method, you can use the global variable $_REQUEST. Sample code bellow:

<html>
<body>
<form method="POST" action="postdata.php">
<input type="text" name="mydata" />
<input type="submit">
</form>
</body>
</html>

file postdata.php:

<?php

$result = $_POST['mydata'];
echo $result;
like image 32
Anax Avatar answered Sep 19 '22 20:09

Anax