Skip to content
Advertisement

PHP: How to escape HTML form input multidimensional keys

I have form that have input fields with multidimensional keys. And keys contains XPath queries.

When i submit my form, keys of array spoiling.

This is simple example of my code.

<!DOCTYPE html>
<html>
<body>
<?php if (isset($_POST['key'])){
    var_dump($_POST['key']);
}

$attr = '//*[self::textarea or self::input]/@placeholder';
?>
<form action="" method="post">

    <input type="text" name="key[1][<?php echo $attr;?>]">

    <input type="submit" value="Submit">
</form>

</body>
</html>

Response of var_dump

array(1) {
  [1]=>
  array(1) {
    ["//*[self::textarea or self::input"]=>
    string(3) "asd"
  }
}

How can i escape keys. I hope someone can give an answer.

Please do not offer to resolve this issue with json or with another way.

Advertisement

Answer

You can use urlencode to escape the $attr value, and then use array_walk over $_POST['key'] to replace the keys with their urldecode version:

if (isset($_POST['key'])) {
    array_walk($_POST['key'], function (&$a) {
        $a = array(urldecode(key($a)) => current($a));
    });
}
var_dump($_POST);

$attr = '//*[self::textarea or self::input]/@placeholder';
?>
<form action="" method="post">

    <input type="text" name="key[1][<?php echo urlencode($attr);?>]">

    <input type="submit" value="Submit">
</form>

Output:

array(1) {
  ["key"]=>
  array(1) {
    [1]=>
    array(1) {
      ["//*[self::textarea or self::input]/@placeholder"]=>
      string(3) "asd"
    }
  }
}

If you have multiple elements under each numeric key value, you will need to use a foreach within the array_walk:

if (isset($_POST['key'])) {
    array_walk($_POST['key'], function (&$a) {
        foreach ($a as $key => $value) {
            $a[urldecode($key)] = $value;
            unset($a[$key]);
        }
    });
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement