<?php
$x = array("<b>","<i>","b","i","<h1>hello</h1>");
print_r ($x);
echo "<hr>";
var_dump ($x);
将其输出到 html 源代码中!
Array
(
[0] => <b>
[1] => <i>
[2] => b
[3] => i
[4] => <h1>hello</h1>
)
<hr>array(5) {
[0]=>
string(3) "<b>"
[1]=>
string(3) "<i>"
[2]=>
string(1) "b"
[3]=>
string(1) "i"
[4]=>
string(14) "<h1>hello</h1>"
}
显然,我可能会因此受到 XSS 攻击!
如何确保数组值经过 html 编码?
虽然这个问题有一个公认的答案,但我认为 David Morrow 的答案是最好/最简单/最实用的(使用
print_r
true
标志):
echo "<pre>".htmlentities(print_r($some_array, true))."</pre>";
尽管如此,这是另一种使用输出缓冲的解决方案:
<?php
ob_start();
print_r($some_array);
$buffer = ob_get_clean();
echo "<pre>".htmlentities($buffer)."</pre>";
?>
我发现knittl的代码不起作用。我必须进行一些小更改才能使其正常工作,如下所示:
array_walk_recursive($inputarray, function(&$v) { $v = htmlspecialchars($v); });
现在这在 PHP5.3+ 中工作得很好
或者您可以将 print_r 保存到字符串中,然后使用设置为 true 的第二个参数对其进行转义。
$arr = array('<script>alert("hey");</script>');
$str = print_r($arr, true);
echo htmlentities($str);
输出:
Array
(
[0] => <script>alert("hey");</script>
)
脚本未执行
这个 PHP 手册注释中描述了一个对我有用的函数。
他替换var_dump
的函数实现为:
function htmlvardump()
{
ob_start();
$var = func_get_args();
call_user_func_array('var_dump', $var);
echo htmlentities(ob_get_clean());
}
这在 PHP 5.3+ 中对我有用。
(请注意,原始来源中有一个拼写错误)。
echo <pre>;
echo htmlspecialchars(print_r($key['value'], true));
echo '</pre>';
我使用此代码从无sql数据库输出数组值(包含adsense代码)。
<?php
$x = array("tag1" => "<b>","tag2" => "<i>","tag3" => "b","tag4" => "i","tag5" => "<h1>hello</h1>");
echo "<hr><pre>";
blp_print_r ($x);
echo "<hr>";
print_r($x);
echo "</pre><hr>";
/*
outputs this in the browser normal view
new one...
Array
(
['tag1'] => <b>
['tag2'] => <i>
['tag3'] => b
['tag4'] => i
['tag5'] => <h1>hello</h1>
)
traditional one...
Array
(
[tag1] =>
[tag2] =>
[tag3] => b
[tag4] => i
[tag5] =>
hello
)
*/
function blp_print_r($inputarray){
echo "Array\n(\n";
echo "<blockquote>";
array_walk($inputarray,"html_encoder");
echo "</blockquote>";
echo ")";
}
function html_encoder($current_val,$current_key){
echo "['" , htmlentities($current_key, ENT_QUOTES, "UTF-8") , "']", " => ";
echo htmlentities($current_val, ENT_QUOTES, "UTF-8") , "\n";
}
?>
function htmlentities_print_r( $inputarray ) {
echo "<pre>" ;
array_walk( $inputarray , "html_encoder" ) ;
echo "</pre>";
}
function html_encoder($current_val,$current_key){
echo "['" , htmlentities($current_key, ENT_QUOTES, "UTF-8") , "']", " => ";
if ( is_array( $current_val ) ) {
blp_print_r( $current_val ) ;
} else {
echo htmlentities($current_val, ENT_QUOTES, "UTF-8") , "\n";
}
}
$ret = htmlentities( print_r( $some_array, true ) )
$ret = str_replace( array("\n"), array('<br>'), $ret );
printf( "<br>Result is: <br>%s<br>", $ret );
但这取决于你们所有人。