Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

var_dump or print_r and html encoding

<?php 

$x = array("<b>","<i>","b","i","<h1>hello</h1>");
print_r ($x);
echo "<hr>";
var_dump ($x);

outputs this in the html source!

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>"
}

obviously, I could have been XSS'ed by that!
How can I make sure that the array values are htmlencoded?

like image 526
Average Joe Avatar asked Apr 07 '12 16:04

Average Joe


2 Answers

echo <pre>;
echo htmlspecialchars(print_r($key['value'], true));
echo '</pre>';

I use this code to output an array value (contains adsense code) from no sql database.

like image 197
Raymond Avatar answered Oct 16 '22 20:10

Raymond


While this question has an accepted answer, I think David Morrow's answer is the best/ simplest/ most practical (uses the print_r true flag):

echo "<pre>".htmlentities(print_r($some_array, true))."</pre>";

Never-the-less, here is another solution that uses output buffering:

<?php

ob_start();
print_r($some_array);
$buffer = ob_get_clean();
echo "<pre>".htmlentities($buffer)."</pre>";

?>
like image 35
Self Evident Avatar answered Oct 16 '22 21:10

Self Evident