PHP: How should I escape a string that will be going into a Javascript String?


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

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


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); ?>");

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("<?php echo addslashes($message); ?>");
    
    // ]]>
    </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.


addslashes should be fine.