Friday, October 24, 2025
HomeLanguagesHow to receive JSON POST with PHP ?

How to receive JSON POST with PHP ?

In this article, we will see how to retrieve the JSON POST with PHP, & will also see their implementation through the examples. First, we will look for the below 3 features:

  • php://input: This is a read-only stream that allows us to read raw data from the request body. It returns all the raw data after the HTTP headers of the request, regardless of the content type.
  • file_get_contents() function: This function in PHP is used to read a file into a string.
  • json_decode() function: This function takes a JSON string and converts it into a PHP variable that may be an array or an object.

It is known that all of the post data can be received in a PHP script using the $_POST[] global variable. But this fails in the case when we want to receive JSON string as post data. To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

Handling JSON POST requests:

// Takes raw data from the request
$json = file_get_contents('php://input');

// Converts it into a PHP object
$data = json_decode($json);

Example 1: This example uses the json_decode() function that is used to decode a JSON string.

PHP




<?php
  $json = '["neveropen", "for", "neveropen"]';
  $data = json_decode($json);
  echo $data[0];
?>


Output: 

neveropen

 

Example 2: This example uses the json_decode() function that is used to decode a JSON string.

PHP




<?php
  $json = '{
      "title": "PHP",
      "site": "neveropen"
  }';
  $data = json_decode($json);
  echo $data->title;
  echo "\n";
  echo $data->site;
?>


Output: 

PHP
neveropen

 

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS