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

后端 未结 4 731
南笙
南笙 2021-01-28 20:50

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

相关标签:
4条回答
  • 2021-01-28 21:25

    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

    0 讨论(0)
  • 2021-01-28 21:29

    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); ?>");
    
    0 讨论(0)
  • 2021-01-28 21:30

    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.

    0 讨论(0)
  • 2021-01-28 21:34

    addslashes should be fine.

    0 讨论(0)
提交回复
热议问题