Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: json_decode not working

Tags:

json

php

This does not work:

$jsonDecode = json_decode($jsonData, TRUE);

However if I copy the string from $jsonData and put it inside the decode function manually it does work.

This works:

$jsonDecode = json_decode('{"id":"0","bid":"918","url":"http:\/\/www.google.com","md5":"6361fbfbee69f444c394f3d2fa062f79","time":"2014-06-02 14:20:21"}', TRUE);

I did output $jsonData copied it and put in like above in the decode function. Then it worked. However if I put $jsonData directly in the decode function it does not.

var_dump($jsonData) shows:

string(144) "{"id":"0","bid":"918","url":"http:\/\/www.google.com","md5":"6361fbfbee69f444c394f3d2fa062f79","time":"2014-06-02 14:20:21"}"

The $jsonData comes from a encrypted $_GET variable. To encrypt it I use this:

$key = "SOME KEY";

$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

$enc = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_ECB, $iv);

$iv = rawurlencode(base64_encode($iv));
$enc = rawurlencode(base64_encode($enc));

//To Decrypt
$iv = base64_decode(rawurldecode($_GET['i']));
$enc = base64_decode(rawurldecode($_GET['e']));

$data = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $enc, MCRYPT_MODE_ECB, $iv);
like image 673
yoshi Avatar asked Jun 02 '14 18:06

yoshi


4 Answers

some time there is issue of html entities, for example \" it will represent like this \&quot, so you must need to parse the html entites to real text, that you can do using html_entity_decode() method of php.

$jsonData = stripslashes(html_entity_decode($jsonData));

$k=json_decode($jsonData,true);

print_r($k);
like image 134
user2987827 Avatar answered Nov 07 '22 10:11

user2987827


Most likely you need to strip off the padding from your decrypted data. There are 124 visible characters in your string but var_dump reports 144. Which means 20 characters of padding needs to be removed (a series of "\0" bytes at the end of your string).

Probably that's 4 "\0" bytes at the end of a block + an empty 16-bytes block (to mark the end of the data).

How are you currently decrypting/encrypting your string?

Edit:

You need to add this to trim the zero bytes at the end of the string:

$jsonData = rtrim($jsonData, "\0");
like image 13
laurent Avatar answered Nov 07 '22 08:11

laurent


You have to use preg_replace for avoiding the null results from json_decode

here is the example code

$json_string = stripslashes(html_entity_decode($json_string));
$bookingdata =  json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string), true ); 
like image 12
Hassan Qasim Avatar answered Nov 07 '22 10:11

Hassan Qasim


Judging from the other comments, you could use,

$jsonDecode = json_decode(trim($jsonData), TRUE);
like image 7
dar7yl Avatar answered Nov 07 '22 10:11

dar7yl