Putting this as an answer for the code formatting, but...
@luhiz: think of what happens you're inserting data into a javascript block that contains javascript "meta characters". Let's say you're passing a person's full name as a query parameter, like this:
http://example.com/index.php?name=John+O'toole
In PHP, you'll have:
$_GET['name'] = "John O'toole";
and when you place it into the javascript block, you'll get:
var name = John O'toole;
Now you've got a few problems:
- You've inserted raw user-hackable data into your page
- A javascript syntax error as your string is not enclosed in quotes
- Another syntax error as the name contains a single quote, which begins a string which is then not terminated with another quote.
Discussion:
- This is a classic XSS (cross-site-scripting) attack. You're placing user-provided data into an html page without any safety. The simplest attack example is to use
http://example.com/index.php?name=alert("you've been hacked!");
. Try it and see what happens.
2&3: By using json_encode, PHP automatically converts whatever you're encoding into syntactically safe Javascript. This doesn't mean it's "safe" code - it can still contain malicious data. But it will not cause a syntax error when the page is loaded by the client browser. So by doing:
var name = <?php echo json_encode($_GET['name']);
you'll get something like:
var name = "John O'toole";
which the javascript interpreter will accept without any complaints.