Detect bad json data in PHP json_decode()?

Detect bad json data in PHP json_decode()?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Handling Non-String Input in json_decode()

When validating JSON payloads in PHP, a common trap involves how the function behaves when the input is not a string. The standard usage pattern looks like this:

if (!json_decode($_POST)) {
    echo "bad json data!";
    exit;
}

This logic assumes that $_POST will always be a string or that json_decode() can safely handle whatever is passed to it. However, if the HTTP request sets the content type to application/x-www-form-urlencoded instead of application/json, $_POST becomes an indexed array of strings rather than a single JSON-encoded string.

When this happens, json_decode() throws a warning because it expects a string parameter but receives an array. While the function returns false in both valid and invalid cases, the difference lies in the presence of the PHP warning. The warning gets printed to the output (or error log), which can break your application's response, expose internal paths like C:\server\..., or clutter logs with irrelevant noise.

The core issue here is that json_decode() does not perform type checking on its input before attempting to parse it. If you pass an array, a boolean, or a null value directly, PHP will raise a warning unless you suppress errors or validate the variable beforehand.

Validating Input Before Decoding

To handle this robustly, you must ensure that the data passed to json_decode() is strictly a string. The most reliable approach is to check the type of the variable before calling the function. You can use the is_string() helper:

$input = $_POST; // This might be an array or a string depending on Content-Type

if (!isset($input) || !is_string($input)) {
    // Handle non-JSON input, e.g., form data or missing payload
    http_response_code(400);
    echo "Invalid content type or missing JSON body";
    exit;
}

$jsonData = json_decode($input, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    // Handle malformed JSON string
    http_response_code(400);
    echo "Malformed JSON data";
    exit;
}

This pattern separates concerns: first, verify the data type; second, attempt decoding; third, check the last error code using json_last_error(). This prevents warnings from leaking into your response and ensures that malformed syntax is caught explicitly.

Why Type Checking Matters

Relying solely on the return value of json_decode() is risky because it returns false for both a valid empty object ({}) and an invalid string ("invalid"). The distinction is made via json_last_error(). However, if the input type is wrong (e.g., an array), the function never even reaches the parsing logic to return false; instead, PHP's engine intercepts the call and raises a warning.

Suppressing these warnings with @ silences the error but hides debugging information. A better strategy is to validate the input structure first. In modern frameworks like Laravel, this validation often happens automatically based on the request attributes. For standalone scripts or legacy codebases, explicit type checking remains the safest bet.

Best Practices for JSON Validation

Always assume that external inputs can come in any format. Even if your API contract specifies application/json, clients might misconfigure their headers or send form data by mistake. Your validation logic should be defensive:

  1. Check the variable type: Ensure the input is a string before passing it to json_decode().
  2. Use json_last_error(): After decoding, always check if the result was successful rather than relying on truthiness.
  3. Handle errors gracefully: Return appropriate HTTP status codes (like 400 Bad Request) instead of echoing generic messages that might leak stack traces or internal details.

By implementing these checks, you eliminate the warning noise and create a more predictable error handling flow that works regardless of how the client sends the request.

Our network