3

In my PHP application, I have lots of places where I get POST data and have to convert it to htmlspecialchars, so I find myself having to specify and convert each element in $_POST individually. Here's an example:

$tusername=htmlspecialchars($_POST['username'], ENT_QUOTES,'UTF-8');
$tfname=htmlspecialchars($_POST['firstname'], ENT_QUOTES,'UTF-8');
$tlname=htmlspecialchars($_POST['lastname'], ENT_QUOTES,'UTF-8');
$temail=htmlspecialchars($_POST['email'], ENT_QUOTES,'UTF-8');
$tskill=htmlspecialchars($_POST['skillsearchpriv'], ENT_QUOTES,'UTF-8');

This can get tedious, especially when you have over +10 $_POST variables for multiple forms.

Is there away of converting all POST variables to htmlspecialchars at once?

Something like $_POST=htmlspecialchars($_POST[allkeys], ENT_QUOTES,'UTF-8');?

dlofrodloh
  • 1,728
  • 3
  • 23
  • 44
  • Did you find that any of these answers was helpful? You have neither accepted any of them, nor made any comment as feedback. – Ifedi Okonkwo Oct 05 '15 at 13:49

4 Answers4

13

One way to go is array_map(), which provides you a means of applying a particular function call (referred to as a callback) to each element of an array.

 $newpost = array_map ( 'htmlspecialchars' , $_POST );

Then you can get $newpost['firstname'], etc

Ifedi Okonkwo
  • 3,406
  • 4
  • 33
  • 45
3

A simple foreach loop should suffice.

<?php

foreach ($_POST as $key => $value) {
    $_POST[$key] = htmlspecialchars($value, ENT_QUOTES,"UTF-8");
}

?>

Reading Material

Performance of foreach, array_map with lambda and array_map with static function

Community
  • 1
  • 1
Script47
  • 14,230
  • 4
  • 45
  • 66
  • Looking through the "Reading Material", I get the impression that the performance differences might have come from `xdebug` itself. Didn't you notice that? – Ifedi Okonkwo Oct 04 '15 at 22:21
  • @IfediOkonkwo it was more of a general read as I found it interesting and it was somewhat related to the question. – Script47 Oct 04 '15 at 22:24
2

Something like $_POST=htmlspecialchars($_POST[allkeys], ENT_QUOTES,'UTF-8');?

You shouldn't do this. You use post data also for other thing, and you should use htmlspecialchars only for escape data in your html page.

What you want is to use some template engine like twig, that has automatic escaping enabled by default.

Federkun
  • 36,084
  • 8
  • 78
  • 90
2

use array_walk e.g.

function xss_protect(&$item) {
  $item = htmlspecialchars($item);
}
array_walk($_POST, 'xss_protect');
Rob G
  • 592
  • 4
  • 18