You could just array_map
strip_tags
to $_POST
, but it is much nicer to write a custom function for obtaining data from it:
function post_data($name) {
global $post_cache;
if (in_array($name, $post_cache)) {
return $post_cache[$name];
}
$val = $_POST[$name];
if (is_string($val)) {
$val = strip_tags($val);
} else if (is_array($val)) {
$val = array_map('strip_tags', $val);
}
$post_cache[$name] = $val;
return $val;
}
This will make your code more readable (others looking into it will generally assume that $_POST['foo']
is the data in form field foo
, not somethin you have already preprocessed), won't cause you problems with plugins or libraries which try to access $_POST directly, makes it easy to add more logic to $_POST
preprocessing (unescape when magic quotes are enabled is a common one) without hunting down all the places in your code where you have used POST data, and saves you from huge headaches when you realize there are a few POST fields where you do need HTML tags. Generally, it is a really bad idea to directly change any of the superglobals.
Also, it is better to sanitize data on output, not on input. Different uses will require different methods, for example, if you use
<div class="user_photo">
<img src="<?php echo photo_path($user_id) ?>" alt="<?php echo $user_name ?>" />
</div>
then $user_name
is an XSS attack vector, and strip_tags
does not help against it at all; you would need htmlspecialchars. If user data is used as an URL, you would need yet another method to defend against javascript:
URLs and so on.