PHP: How to receive request Payload


When you use POST method with JSON data, you couldn’t receive request Payload with $_POST, $_GET, or $_REQUEST

ajax request payload

Example, you use ajax to POST JSON data

$.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "ajax/customer",
                data: "{'c_idcard':'" + $(".txt_idcard").val()+ "'}",
                dataType: "json",
                success: function(data) {
                    response(data.d);
                },
                error: function(result) {
                    alert("Error");
                }
            }); 

And PHP code

<?php
var_dump($_POST);
?>

We’ll receive the empty array

array(0) {
}

How to receive request Payload?

Solution 1: Use $HTTP_RAW_POST_DATA

<?php
var_dump($HTTP_RAW_POST_DATA);
?>

Example output:

string(16) "{'c_idcard':'1'}"

Note 1: If you get the error:

Notice: Undefined variable: HTTP_RAW_POST_DATA In D:\AppServ\www\tutorialspots\application\controller\ajax.php At Line 10

You must open php.ini and open line

always_populate_raw_post_data = On

always_populate_raw_post_data

If you place your code in a function, you must set global $HTTP_RAW_POST_DATA

global $HTTP_RAW_POST_DATA;

Note 2: This feature was DEPRECATED in PHP 5.6.0, and REMOVED as of PHP 7.0.0.

Solution 2: use php://input
Example:

<?php
var_dump(file_get_contents('php://input'));
?>

Example output:

string(16) "{'c_idcard':'2'}"

Now, you can receive the request Payload.

Leave a Reply