Escape double quotes of HTML attributes output by PHP

前端 未结 6 1900
春和景丽
春和景丽 2021-01-06 08:36

Often when writing PHP I\'ll have it output some HTML like this -

echo \"\".$link_text.\"\";


        
相关标签:
6条回答
  • 2021-01-06 09:03

    You should just use single-quotes instead:

    echo '<a href="../" title="link title">' . $link_text . '</a>';
    
    0 讨论(0)
  • 2021-01-06 09:09

    use single quotes or use heredoc. I'd prefer the last.

    0 讨论(0)
  • 2021-01-06 09:10

    I think you can use

    http://www.example.com/.../Learning-Tutorials/ACTIVE-USER-ACCOUNT/verify.php?email='.$email.'&hash='.$hash.'
    
    "<a href="//www.example.com/.../Learning-Tutorials/ACTIVE-USER-ACCOUNT/verify.php?email="$email&hash=$hash>Click Here to Active</a>"
    

    try it.

    0 讨论(0)
  • 2021-01-06 09:14

    Use (This syntax dont worry about quotes etc)

    echo <<<EOT
    <a href="../" title="link title">$link_text</a>
    EOT;
    
    0 讨论(0)
  • 2021-01-06 09:16

    I'd strongly suggest using templating instead of trying to build strings.

    In raw PHP:

    <a href="../" title="link title"><?php echo $link_text; ?></a>
    
    0 讨论(0)
  • 2021-01-06 09:20

    Solutions I can come up with (not without escaping):

    • Single quotes

      echo '<a href="../">' . $link_text. '</a>';
      
    • Use double quotes

      echo "<a href='../'>$link_text</a>";
      
    • Sprintf

      echo sprintf('<a href="../">%s</a>', $link_text);
      
    • Use HEREDOC

      echo <<<EOF
      <a href="../">$link_text</a>
      EOF;
      
    • Use template engine like smarty

    • Exit PHP-mode:

      ?><a href="../"><?php echo $link_text ?></a><?php // other code...
      

    BTW, be sure to use htmlspecialchars() on $link_text variable, or you’ll have a XSS security hole.

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