Statement on glibc/iconv Vulnerability

json_validate

(PHP 8 >= 8.3.0)

json_validateChecks if a string contains valid JSON

Description

json_validate(string $json, int $depth = 512, int $flags = 0): bool

Returns whether the given string is syntactically valid JSON. If json_validate() returns true, json_decode() will successfully decode the given string when using the same depth and flags.

If json_validate() returns false, the cause can be retrieved using json_last_error() and json_last_error_msg().

json_validate() uses less memory than json_decode() if the decoded JSON payload is not used, because it does not need to build the array or object structure containing the payload.

Caution

Calling json_validate() immediately before json_decode() will unnecessarily parse the string twice, as json_decode() implicitly performs validation during decoding.

json_validate() should therefore only be used if the decode JSON payload is not immediately used and knowing whether the string contains valid JSON is needed.

Parameters

json

The string to validate.

This function only works with UTF-8 encoded strings.

Note:

PHP implements a superset of JSON as specified in the original » RFC 7159.

depth

Maximum nesting depth of the structure being decoded. The value must be greater than 0, and less than or equal to 2147483647.

flags

Currently only JSON_INVALID_UTF8_IGNORE is accepted.

Return Values

Returns true if the given string is syntactically valid JSON, otherwise returns false.

Errors/Exceptions

If depth is outside the allowed range, a ValueError is thrown.

If flags is not a valid flag, a ValueError is thrown.

Examples

Example #1 json_validate() examples

<?php
var_dump
(json_validate('{ "test": { "foo": "bar" } }'));
var_dump(json_validate('{ "": "": "" } }'));
?>

The above example will output:

bool(true)
bool(false)

See Also

add a note

User Contributed Notes 3 notes

up
12
Behrad
3 months ago
---------------- PHP < 8.3 ----------------

function json_validate(string $string): bool {
    json_decode($string);

    return json_last_error() === JSON_ERROR_NONE;
}

var_dump(json_validate('{ "test": { "foo": "bar" } }')); // true

---------------- PHP >= 8.3 ----------------

var_dump(json_validate('{ "test": { "foo": "bar" } }')); // true

Note: code from https://www.php.net/releases/8.3/en.php
up
4
Julien T.
2 months ago
Building upon Allan R.'s initial idea, I've developed an improved version of the json_validate function for those using PHP 8.2 and earlier versions. This function emulates the functionality introduced in PHP 8.3, providing an effective way to validate JSON strings in earlier PHP versions.

```php
if (!function_exists('json_validate')) {
    /**
     * Validates a JSON string.
     *
     * @param string $json The JSON string to validate.
     * @param int $depth Maximum depth. Must be greater than zero.
     * @param int $flags Bitmask of JSON decode options.
     * @return bool Returns true if the string is a valid JSON, otherwise false.
     */
    function json_validate($json, $depth = 512, $flags = 0) {
        if (!is_string($json)) {
            return false;
        }

        try {
            json_decode($json, false, $depth, $flags | JSON_THROW_ON_ERROR);
            return true;
        } catch (\JsonException $e) {
            return false;
        }
    }
}
```

Key Improvements:

- String Check: Added a validation to ensure the input is a string.
- Error Handling: Utilizes try-catch to effectively catch and handle JsonException.
- Backward Compatibility: Safely integrable in older PHP versions, automatically deferring to native functionality in PHP 8.3+.
up
1
Allan R.
2 months ago
Pre PHP 8.3, and future compatible, function/wrapper

---
if(!function_exists("json_validate")) {
    function json_validate() {
        try {
            json_decode($json, JSON_THROW_ON_ERROR);
            return true;
        } catch(\JsonException) {
            return false;
        }
    }
}
---

An issue with simply relying on json_last_error() == JSON_ERROR_NONE is if you have an error handler that catches errors or notices and throws them instead as  fx. \ErrorException

That would cause a call to json_decode(); to throw an exception exiting the scope of the function.
To Top