doujiyun0041 2015-01-17 15:36
浏览 198

在回显变量时防止XSS攻击

I need to prevent from XSS attacks when I echoing variables in PHP.

For example, just assume I have two values from my database, one for username and the other one is email address.

$username
$email

So now I want to prevent from XSS attack when I using these variables in my HTML.

I tried it something like this using htmlspecialchars() -

<h5>Editing User <?php echo '"<strong>'.htmlspecialchars($username, ENT_QUOTES, 'UTF-8').'"</strong> (<strong>'; echo htmlspecialchars($email, ENT_QUOTES, 'UTF-8').'</strong>)'; ?></h5>

This is rendered HTML from above PHP

<h5>Editing User <strong>test_user</strong> (<strong>example@gmail.com</strong>)</h5>

So, can somebody tell me is this the correct way do I need to go? If not so what is the correct way?

Hope somebody may help me out. Thank you.

  • 写回答

2条回答 默认 最新

  • dt250827 2015-01-17 15:41
    关注

    First of all, the correct way to escape output is htmlentities, not htmlspecialchars.
    Escape ALL output you get from variables, database or user input.
    This is pretty much all you have to do to escape XSS attacks.
    You may also consider using strip_tags where it's appropriate.

    Here you go:

    <h5>
        Editing User <b><?=htmlentities($username)?></b> 
        (<b><?=htmlentities($email)?></b>)
    </h5>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog