2016-04-28 30 views
0

我知道在网页上显示时需要使用htmlspecialchars转义输出。我必须使用htmlspecialchars转义所有输出变量吗?

我只是想知道,我是否需要为每个输出的单个数据执行该操作,或者只有那些用户可能控制的数据位?

例如,下面的第一个代码块没有转义,第二个代码已经转义了。

我是否需要转义一个数据库中的ID和一个只在页面内设置的变量?

或者只有包含用户可以编辑的数据的变量 - 在下面的例子中,它将是$ post_label和$ post_content。在逃跑前

代码:

while ($row = $stmt->fetch()){ 

    $post_id =  $row['ID']; 
    $post_date = $row['post_date']; 
    $post_content = $row['post_content']; 
    $post_label = $row['post_label']; 
    $fld_cat =  $row['fld_cat']; 
    $post_day_num = date('N', strtotime($post_date)); 

    if ($post_day_num > 5) { 
     $css = "success"; 
    } else { 
     $css = "info"; 
    } 

    $recent .= "<div class='alert alert-$css'>\n"; 
    $recent .= " <div>\n"; 
    $recent .= "  <strong>" . date('D d-M-Y', strtotime($post_date)) . " | $fld_cat</strong> | \n"; 
    $recent .= "  <a href='default.php?id=$post_id&amp;mode=edit'>Edit</a> | \n"; 
    $recent .= "  <a href='default.php?id=$post_id&amp;mode=delete'>Delete</a>\n"; 
    $recent .= " </div>\n"; 
    $recent .= " <div>$post_content</div>\n"; 
    $recent .= "</div>\n"; 

} 

代码后逃逸:

while ($row = $stmt->fetch()){ 

    $post_id =  htmlspecialchars($row['ID']); 
    $post_date = htmlspecialchars($row['post_date']); 
    $post_content = htmlspecialchars($row['post_content']); 
    $post_label = htmlspecialchars($row['post_label']); 
    $fld_cat =  htmlspecialchars($row['fld_cat']); 
    $post_day_num = htmlspecialchars(date('N', strtotime($post_date))); 

    if ($post_day_num > 5) { 
     $css = "success"; 
    } else { 
     $css = "info"; 
    } 

    $recent .= "<div class='alert alert-$css'>\n"; 
    $recent .= " <div>\n"; 
    $recent .= "  <strong>" . date('D d-M-Y', strtotime($post_date)) . " | $fld_cat</strong> | \n"; 
    $recent .= "  <a href='default.php?id=$post_id&amp;mode=edit'>Edit</a> | \n"; 
    $recent .= "  <a href='default.php?id=$post_id&amp;mode=delete'>Delete</a>\n"; 
    $recent .= " </div>\n"; 
    $recent .= " <div>$post_content</div>\n"; 
    $recent .= "</div>\n"; 

} 

回答

0

简短的回答是,每次将数据库中的数据转换为HTML时,都应该通过此方法运行,以便正确解释并且不会破坏标记或导致安全漏洞。

当然,如果你对输出有绝对的控制权 - 这不是一定要担心的。然而,核心指导方针是你永远不会有绝对的控制权。

0

只有逃跑用户输入。来自数据库或来自您自己代码的ID或其他内容不能由具有恶意意图的用户操纵。

请记住,转义字符串的主要原因是为了防止跨站点脚本攻击。不是来自用户的输入不能包含XSS代码。

相关问题