Handling JSON Requests in PHP
When submitting data in AJAX requests, the contentType header specifies the format of the data being sent. The default x-www-form-urlencoded encoding encodes data as key-value pairs, while application/json encodes it as a JSON string.
When contentType is set to application/json, PHP's built-in $_POST variable, which holds form parameters, becomes empty. This is because the raw JSON string is not automatically parsed into individual parameters.
To correctly handle JSON requests in PHP, use the following code:
<code class="php"><?php var_dump(json_decode(file_get_contents('php://input'))); ?></code>
file_get_contents('php://input') reads the raw request body. json_decode() then parses the JSON string into a PHP object or array, which can be accessed like any other PHP variable.
Here's an example usage:
<code class="php">// Assume an incoming request with the following JSON body: { "my_params": 123 } // Parse the JSON request $data = json_decode(file_get_contents('php://input')); // Access the parsed data like any other PHP variable $my_params = $data->my_params;</code>
The above is the detailed content of How to Handle JSON Requests in PHP?. For more information, please follow other related articles on the PHP Chinese website!