The fact that $GLOBALS
contains reference to itself results in an infinite recursion that json_encode
can't handle because it exceeds the maximum depth of 512 and thus will return false
by default.
The solution would be creating a copy of $GLOBALS
without self-referencing, the function below references superglobals _GET _POST _SERVER ..
only, assuming you don't use $_
in your variables naming conventions:
function getEncodableGlobals()
{
$g = [];
foreach ($GLOBALS as $key => &$val)
{
if ($key[0] == '_')
{
$g[$key] = &$val;
}
}
return $g;
}
Notice that $g
doesn't hold copies but only references to variables, just like $GLOBALS
does. If you wish to include all the variables in the global scope simply change the condition to exclude the troublesome reference:
...
if ($key !== 'GLOBALS')
...
Now you can safely encode it:
json_encode(
getEncodableGlobals()
);
You could also do it the array_filter
way and copy the variables.
$encodableGlobals = array_filter($GLOBALS, function($key) {
return $key !== 'GLOBALS';
}, ARRAY_FILTER_USE_KEY);