Statement
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:
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:
returns:
It is still a string, not usable as an array.
3️⃣ json_decode(..., true)
json_decode() converts JSON string into PHP data.
Syntax:
The second parameter:
-
true→ return associative array -
false(default) → return object
So:
Now $data becomes:
4️⃣ Full Example API Usage
5️⃣ Why Not Use $_POST?
$_POST works only when:
-
Content-Type:
application/x-www-form-urlencoded -
Or
multipart/form-data
If frontend sends:
Then $_POST will be empty.
That is why APIs use php://input.
6️⃣ Best Practice (Safe Version)
Always check for errors:
Summary
| Part | Meaning |
|---|---|
php://input | Raw HTTP request body |
file_get_contents() | Reads the raw body |
json_decode() | Converts JSON string to PHP data |
true | Return associative array |