How should I escape a string that will be going into a Javascript String? URLEncode(X)? str_replace("'","\'",X)?
- 
                    Is this (discouraged) inline javascript (``) or in a separate script block? – Pekka Aug 17 '10 at 15:25
4 Answers
use json_encode
so you can do
$page_params = array(
    'user_logged_in' => $suer->IsActive(),
    'some_string' => "sajdhf\"test''z\'\fsdf"
    'ts' => time()
);
$page_params = json_encode($page_params);
then in your template you can just go
var page_params = <?php echo $page_params ?>;
witch would produce
var page_params = {"user_logged_in":false,"some_string":"sajdhf\"test''z\'\fsdf","ts":2452346543}
this way you can set multiple variables to 1 string and escaping is done by the Json Library
 
    
    - 56,863
- 21
- 114
- 161
Use json_encode if available (since PHP 5.2):
var str = <?php echo json_encode($str); ?>;
Otherwise use you can use rawurlencode and decode it with decodeURIComponent:
var str = decodeURIComponent("<?php echo rawurlencode($str); ?>");
 
    
    - 643,351
- 109
- 780
- 844
There a couple of things you should do to escape your input. At a minimum do #1:
- The addslashes function will add backslashes before single ( - ') and double (- ") quotes, backslashes (- \), and NUL (- \0).
- For extra safety wrap your entire script section in CDATA tags so you can validate the script as XHTML even if it contains - <or- >:- <script> // <![CDATA[ alert("<?php echo addslashes($message); ?>"); // ]]> </script>
- Also if you're really paranoid you'll break up any occurrences of - </script>and- ]]>since those can interfere with the HTML parser. For example, replace- </script>with- <"+"/script>and- ]]>with- ]]"+">. Again that depends on how anal you are about protecting yourself from malicious/questionable user input.
 
    
    - 349,597
- 67
- 533
- 578
 
    