Escape quotes in a variable with PHP

后端 未结 7 676
温柔的废话
温柔的废话 2021-01-12 03:16

I use this code to genefate html

echo \"\";

Everything would be OK unles

7条回答
  •  时光取名叫无心
    2021-01-12 03:36

    Whenever thinking about escaping, you always need to ask
    "In which context do I want to escape?"
    Because escaping is essentialy making sure the input is not interpreted in the special meaning of the target, but literaly

    Do not use addslashes, since it's contextless

    If you are inserting the string into HTML, use

    htmlspecialchars($argument, ENT_QUOTES)
    

    as mentioned.

    The onclick content part is technicaly JavaScript, so it might be appropriate to escape the content with json_encode (it's side-effect is JavaScript-specific escaping). Similarly should you have style attribute, you'd want to escape the content with

    addcslashes($s, "\x00..\x2C./:;<=>?@[\\]^`{|}~")
    

    (source: http://translate.google.com/translate?u=http%3A%2F%2Fphpfashion.com%2Fescapovani-definitivni-prirucka&ie=UTF8&sl=cs&tl=en)

    Summary
    Use

    $param = htmlspecialchars(json_encode($param), ENT_QUOTES)
    

    and then you can safely include it into the HTML string

提交回复
热议问题