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

后端 未结 4 784
南笙
南笙 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: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 >:

      
      
    3. Also if you're really paranoid you'll break up any occurrences of and ]]> since those can interfere with the HTML parser. For example, replace with <"+"/script> and ]]> with ]]"+">. Again that depends on how anal you are about protecting yourself from malicious/questionable user input.

提交回复
热议问题