Statement on glibc/iconv Vulnerability

json_validate

(PHP 8 >= 8.3.0)

json_validateVerifica se uma string contém JSON válido

Descrição

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

Retorna se a string informada é um JSON válido sintaticamente. Se json_validate() retornar true, json_decode() irá decodificar com sucesso a string informada ao usar a mesma profundidade de depth e as opções em flags.

Se json_validate() retornar false, a causa pode ser obtida usando json_last_error() e json_last_error_msg().

json_validate() usa menos memória que json_decode() se o JSON decodificado não for usado, porque ela não precisa construir o array ou a estrutura de objeto que contém a decodificação.

Cuidado

Chamar json_validate() imediatamente antes de json_decode() irá analisar a string duas vezes desnecessariamente, já que json_decode() implicitamente realiza a validação durante a decodificação.

Portanto, json_validate() deve somente ser utilizada se o JSON decodificado não for usado imediatamente e se for necessário saber se a string contém JSON válido.

Parâmetros

json

A string a ser validada.

Esta função funciona somente com strings codificadas com UTF-8.

Nota:

O PHP implementa um superconjunto de JSON conforme especificado na » RFC 7159 original.

depth

A máxima profundidade de aninhamento da estrutura sendo decodificada. O valor precisa ser maior que 0, e menor ou igual a 2147483647.

flags

Atualmente apenas a constante JSON_INVALID_UTF8_IGNORE é aceita.

Valor Retornado

Retorna true se a string fornecida for um JSON válido sintaticamente, caso contrário retorna false.

Erros/Exceções

Se depth estiver fora do intervalo permitido, uma exceção ValueError é lançada.

Se flags não for uma opção válida, uma exceção ValueError é lançada.

Exemplos

Exemplo #1 Exemplos de json_validate()

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

O exemplo acima produzirá:

bool(true)
bool(false)

Veja Também

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