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

[亡魂溺海] 提交于 2019-12-02 08:06:15

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!