简体   繁体   中英

json_encode combined with $_GET (PHP & Javascript)

I need to pass a JSON array into a webpage URL so I do

$url = 'page.php?id=' . json_encode($array);

which becames

$url = 'pages.php?id=["1", "2", "3"]';

And then, inside page.php which is basically Javascript code i do

var foo = <?php $_GET['id']; ?>

But foo instead of being an array like ["1", "2", "3"] it's only [ .

Why is this?

Also, is it better to do: url.php?id=value or url.php?id="value" ??

You forgot to urlencode() it.

$url = 'page.php?id=' . urlencode(json_encode($array));

And don't forget to json_decode() it when it gets back.

Out of curiosity do you have to pass it as a json_encoded string?

Perhaps you could pass it as an array

page.php?id[]=1&id[]=2&id[]=3 

then your page.php code would look like this:

echo json_encode($_GET['id']);

I would also check for bad data using a white list approach if your passing in page ids.

$safe = array('1','2','3');
$id = $_GET['id'];
foreach($id as $value){
 if(!in_array($value, $safe)){
    echo "Sry, data not valid";
    exit;
 }
}
echo json_encode($id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM