Pages

PHP: Explain json_decode(file_get_contents("php://input"), true);

Statement

json_decode(file_get_contents("php://input"), true);

This line is commonly used in PHP APIs to read incoming JSON data from an HTTP request and convert it into a usable PHP array.


1️⃣ php://input

php://input is a read-only stream that gives access to the raw body of the HTTP request.

It is used when:

  • The request method is POST, PUT, PATCH, etc.

  • The client sends JSON data (not form-data).

Example request body sent from frontend:

{ "name": "Raju", "age": 25 }

php://input contains this raw JSON string.


2️⃣ file_get_contents("php://input")

This function reads the raw request body as a string.

So this part:

file_get_contents("php://input")

returns:

'{"name":"Raju","age":25}'

It is still a string, not usable as an array.


3️⃣ json_decode(..., true)

json_decode() converts JSON string into PHP data.

Syntax:

json_decode(string $json, bool $associative);

The second parameter:

  • true → return associative array

  • false (default) → return object

So:

$data = json_decode(file_get_contents("php://input"), true);

Now $data becomes:

[ "name" => "Raju", "age" => 25 ]

4️⃣ Full Example API Usage

$data = json_decode(file_get_contents("php://input"), true); $name = $data['name']; $age = $data['age']; echo "Name: $name, Age: $age";

5️⃣ Why Not Use $_POST?

$_POST works only when:

  • Content-Type: application/x-www-form-urlencoded

  • Or multipart/form-data

If frontend sends:

Content-Type: application/json

Then $_POST will be empty.

That is why APIs use php://input.


6️⃣ Best Practice (Safe Version)

Always check for errors:

$rawData = file_get_contents("php://input"); $data = json_decode($rawData, true); if (json_last_error() !== JSON_ERROR_NONE) { http_response_code(400); echo json_encode(["error" => "Invalid JSON"]); exit; }

Summary

PartMeaning
php://inputRaw HTTP request body
file_get_contents()Reads the raw body
json_decode()Converts JSON string to PHP data
trueReturn associative array


No comments:

Post a Comment