php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #75746 empty string is (wrongly) accepted as valid json
Submitted: 2017-12-30 00:51 UTC Modified: 2017-12-30 08:48 UTC
From: php at richardneill dot org Assigned:
Status: Not a bug Package: JSON related
PHP Version: 7.2.0 OS: Linux
Private report: No CVE-ID: None
 [2017-12-30 00:51 UTC] php at richardneill dot org
Description:
------------
In order to validate whether a given string is legitimate JSON, the documentation at: http://php.net/manual/en/function.json-decode.php suggests that we run it through json_decode() and then check that json_last_error() is JSON_ERROR_NONE.

However, when the string is empty, json_last_error() is not set.

The empty string is not syntactically valid as json.

Test script:
---------------
$checkme = '';
json_decode($checkme);
if (json_last_error() === JSON_ERROR_NONE){
	echo "OK";
}else{
	echo "FAIL";
}

#This should result in "FAIL", 
#but it gives "OK", wrongly imho.

Expected result:
----------------
json_decode('');
should set json_last_error().

Actual result:
--------------
[Note: this seems to be very similar to the same issue in bugs 54484 and 68938, both of which were fixed and closed on the PHP 5 series]

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-12-30 01:32 UTC] danack@php.net
-Status: Open +Status: Feedback
 [2017-12-30 01:32 UTC] danack@php.net
I think the fix was applied to 7.0+, not to the 5 series: https://3v4l.org/0MCkJ

Changing the code slightly to be more explicit:

$checkme = '';
json_decode($checkme);
if (json_last_error() === JSON_ERROR_NONE){
	echo "No error.";
}else{
	echo "error detected of : " . json_last_error() . " " . json_last_error_msg();
}


Gives the output:

Output for 7.0.0 - 7.2.0
error detected of : 4 Syntax error

Output for 5.6.0 - 5.6.30, hhvm-3.18.5 - 3.22.0
No error.

Can you confirm it's actually ok in 7, and just has the legacy behaviour in 5?
 [2017-12-30 02:17 UTC] php at richardneill dot org
-Status: Feedback +Status: Closed
 [2017-12-30 02:17 UTC] php at richardneill dot org
Oh bother. It turns out that this particular machine has got both mod-php7 and mod-php5 on it. And while /usr/bin/php gives precedence to 7.x, apache gives precendence to 5.x. So yes, it's legacy behaviour in 5, and working correctly in 7, and while I thought I was running 7, I actually wasn't. Please close this bug as E_REPORTER_IS_A_DOZY_TWIT.  Sorry to have filed a dud report.
 [2017-12-30 08:48 UTC] requinix@php.net
-Status: Closed +Status: Not a bug
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Tue Apr 16 14:01:29 2024 UTC