0

json_decode works for strings that were recently encoded, but not from strings read from files?

<?
$ips=fopen("e","r+");
var_dump(fread($ips,
filesize('e'))); // Returns 'string(190) "[["37.19.199.140"]]"'
$aga=json_decode(fread($ips,filesize('e')));
echo ($aga); // Returns nothing. Why?
if(gettype($aga)!="array"){
    $aga=[];
}
$aga[count($aga)]=[$_SERVER['REMOTE_ADDR']];
ftruncate($ips,0);
fwrite($ips,json_encode($aga));
fclose($ips);
echo '<div>';
var_dump(json_encode($aga)); // Returns 'string(19) "[["37.19.199.140"]]"'
echo '<div>';
var_dump(json_decode(json_encode($aga))); // Returns 'array(1) { [0]=> array(1) { [0]=> string(13) "37.19.199.140" } }'
?>

This is my code. Apparently the string in my file is 190 characters, but the string created within the script is 19 characters? They look the same when printed out. Why does json_decode work for the string created inside the script, but not the string from the file? Here is the output.

string(190) "[["37.19.199.140"]]"
string(19) "[["37.19.199.140"]]"
array(1) { [0]=> array(1) { [0]=> string(13) "37.19.199.140" } }`

I tried making an IP logger that logs IP as a JSON array inside of a file. I expected it to work simply, but instead apparently json_decode doesn't work for what was attained from the file.

  • 1
    `[["37.19.199.140"]]` is not 190 characters. There are a ton of invisible characters in there that is being stripped out. – aynber Feb 16 '23 at 13:51
  • Ah, I just checked the "e" file with a text editor. There's lots of invisible characters in front of it all. I probably used ftruncate incorrectly. How do you open a file with read and write permissions, read the file, THEN wipe it? Because using "w+" with fopen wipes out the file immediately so I can't read it. – stairtheref Feb 16 '23 at 13:55
  • 1
    You _could_ just read it with file_get_contents and then overwrite it with file_put_contents. Unless you desperately need to lock it in between those commands, it's likely to be a lot easier than messing about with file handles and so on. – ADyson Feb 16 '23 at 13:58

0 Answers0