sgrontflix sgrontflix - 1 month ago 9
PHP Question

htmlentities() returns empty string when used with an array

When I use

htmlentities()
to encode a variable it works like a charm, but if I do the same thing with an array it just returns an empty array. I tried to use
array_map()
but it's the same story. I tried to switch the encoding to
ISO-8859-1
and
UTF-8
but with no success. It doesn't want to work.

Here's the code:

<html>
<head>
<title>Signup</title>
</head>
<body>
<form name="signup" method="POST" action="form.php">
<fieldset>
<legend><p style="color:red; font-size:16px">Sports</p></legend>
<ul>
<li>
<input type="checkbox" name="sports[]" value="soccer">
<label for="soccer">Soccer</label>
</li>
<li>
<input type="checkbox" name="sports[]" value="water_polo">
<label for="water_polo">Water polo</label>
</li>
<li>
<input type="checkbox" name="sports[]" value="tennis">
<label for="tennis">Tennis</label>
</li>
<li>
<input type="checkbox" name="sports[]" value="volleyball">
<label for="volleyball">Volleyball</label>
</li>
</ul>
</fieldset>
</form>
<?php
$sports = htmlentities($_POST["sports"], ENT_COMPAT, 'ISO-8859-15');

$count = count($sports);
if($count == 0) {
echo "You don't play any sports.<br>";
} else {
echo "You like playing: ";
foreach($sports as $s) {
if(--$count == 0) {
echo "<span style='color:red'>$s</span>.<br>";
break;
} else {
echo "<span style='color:red'>$s</span>, ";
}
}
}
?>
</body>
</html>


It produces the following output:

You don't play any sports.


Meaning htmlentities() wasn't able to encode my array.

Answer

I'm not sure how you've tried using array_map, but the following is one correct approach:

function sanitize($arg) {
    if (is_array($arg)) {
        return array_map('sanitize', $arg);
    }

    return htmlentities($arg, ENT_QUOTES, 'UTF-8');
}
$array = array_map('sanitize', $_POST);

This uses recursion so it will also work with multi-dimensional arrays.