views:

67

answers:

4

How should I escape a string that will be going into a Javascript String? URLEncode(X)? str_replace("'","\'",X)?

A: 

addslashes should be fine.

zneak
A: 

There a couple of things you should do to escape your input. At a minimum do #1:

  1. The addslashes function will add backslashes before single (') and double (") quotes, backslashes (\), and NUL (\0).

  2. 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("&lt;?php echo addslashes($message); ?&gt;");
    
    // ]]> </script>
  3. 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.

John Kugelman
You’re doing it wrong (see http://stackoverflow.com/questions/236073).
Gumbo
A: 

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); ?>");
Gumbo
+2  A: 

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

RobertPitt