Sanitizing Input String from Form

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I'm trying to find a good, solid function that sanitizes string values
for form validation.  The user notes on offer the following:

And a slight revision of this:

These seem to do different things with tag attributes.  So I've
reworked them slightly.  This is what I came up with (apologies for any
indenting weirdness):

/* String Sanitizing Routine

/* global settings */

    // allowed tags
    $G_allowed_tags ='<a><blockquote><br><br

    // prohibitted tag attributes
    $G_strip_tag_atts =

    // attribute replacement (x_attribute_name)
    $G_replace_att = 'xxx_\1';

/* Fx sanitize_string() */
function sanitize_string($string, $allowed_tags=FALSE) {

    // global allowed tags setting
    global $G_allowed_tags;

    // default allowed tags
    if ( !$allowed_tags) {
        $allowed_tags = $G_allowed_tags;

    // clean string
    $string = strip_tags($string, $G_allowed_tags);
    $clean_string = preg_replace('/<(.*?)>/ie',
"'<'.strip_attributes('\1').'>'", $string);

    // return
    return $clean_string;

}    // end Fx

/* Fx strip_attributes() */
function strip_attributes($string) {

    // global settings
    global $G_strip_tag_atts;
    global $G_replace_att;

  // strip forbidden values
    $stripped_string = stripslashes($string);
    $stripped_string = preg_replace("/($G_strip_tag_atts)/ie",
$G_replace_att, $stripped_string);

    // return
    return $stripped_string;

}    // end Fx


This would take an input string like this:

<p><a href="javascript:alert('you clicked');" target="_blank"
onMouseOver = "alert('you moused')">test</a></p>

And render it like this:

<p><a href="xxx_javascript:alert('you clicked');" xxx_target="_blank"
xxx_onMouseOver = "alert('you moused')">test</a></p>

Then, before inserting in a MySQL database, I would run the string


Anything I've missed?  Anything to add?



Re: Sanitizing Input String from Form

look for
class: InputFilter (PHP4 & PHP5, with comments)
  * @project: PHP Input Filter
  * @date: 30-03-2005
  * @version: 1.2.0_php4/5
  * @author: Daniel Morris


Re: Sanitizing Input String from Form

Tom wrote:
Quoted text here. Click to load it

This one is pretty good and highly configureable.. /

Your's looks decent as well.

Site Timeline