views:

249

answers:

4

Some have see that code :

<?php 
echo stripslashes(json_encode(glob("photos-".$_GET["folder"].'/*.jpg')));
?>

it echo a really nice perfect string like that :

["photos-animaux/ani-01.jpg","photos-animaux/ani-02.jpg","photos-animaux/ani-02b.jpg","photos-animaux/ani-03.jpg","photos-animaux/ani-04.jpg","photos-animaux/ani-05.jpg","photos-animaux/ani-06.jpg","photos-animaux/ani-07.jpg","photos-animaux/ani-08.jpg","photos-animaux/ani-09.jpg","photos-animaux/ani-10.jpg","photos-animaux/ani-11.jpg","photos-animaux/ani-12.jpg","photos-animaux/ani-13.jpg","photos-animaux/ani-14.jpg"]

With json encode it shoul send a array so variable[0] should = to photos-animaux/ani-01.jpg

NOW it is only the fisrt caracter of the string..

how a array get converted to string, and how in javascipt to convert string to array to be able to get value [0] [1] etc..

the question is WHEN or WHY the perfect array get converted to string anyway ?

+1  A: 

In order to parse a JSON-encoded string into actual javascript objects, you need to eval() the data returned in order for javascript to execute against the data:

var data = eval(json_string)

Keep in mind that you should only ever run eval on a string when you trust the source and are sure that there is no possibility of a script injection attack, since javascript will run everything present in the string.

Ryan Brunner
Don't do this, use a JSON library which will safely evaluate the data, not executing any code.
Andrew Aylett
+1  A: 

Use one of the JSON libraries listed at the bottom of http://json.org/

David Dorward
+4  A: 

Using JSON.parse(), from the library available here, is preferable to using eval() since this only reads JSON strings and hence avoids the inherant security risks associated with eval().

Andy
A: 

WHEN or WHY

If I understood correctly, the answer to both is json_encode(): check out the documentation. Converting a variable to a string (often called serialization or flattening) is a quite common operation.

ntd