0

I'm having a problem inserting a less than sign "<" followed by another character let's say "<p" or something like "<---me". Im passing thru this function:

function checkValues($value)
{
    $value = trim($value);
    if (get_magic_quotes_gpc()) 
    {
        $value = stripslashes($value);
    }
    $value = strtr($value,array_flip(get_html_translation_table(HTML_ENTITIES)));

    $value = strip_tags($value); //this line doesnt accept lessthan  

    $value = mysql_real_escape_string($value);
    $value = htmlspecialchars ($value);
    return $value;
}

I know if I remove the strip_tags() lessthan sign will be accepted, but is it safe to save it to the database right after passing thru my function? Or is there a way to let the lessthan sign pass through this function without any problem on saving to database?

Red Mike
  • 29
  • 1
  • 7
  • See http://stackoverflow.com/questions/4995962/how-to-strip-tags-in-a-safer-way-than-using-strip-tags-function – lizbit Feb 10 '12 at 22:28

1 Answers1

4

You shouldn't save sanitized user data to database (htmlspecialchars()). You should sanitize it before outputing, to prevent problems.

Actually, there's nothing wrong with putting < sign into database. Just be sure to use right sanitization in the right context (don' use htmlspecialchars() after mysql_real_escape_string())

your function has a lot of mistakes, look at this example:

This value would be created in your function

\&quot;

This value should be created in your function

\"

which is really wrong

So what should your function(s) look like?

function checkValues($value)
{
    $value = trim($value);
    if (get_magic_quotes_gpc()) 
    {
        $value = stripslashes($value);
    }

    $value = mysql_real_escape_string($value);
    return $value;
}

// just before outputing
function beforeOutput($value) {
    return htmlspecialchars($value);
}
Martin.
  • 10,494
  • 3
  • 42
  • 68
  • @RedMike: See also [Method for sanitizing user input](http://stackoverflow.com/questions/129677/whats-the-best-method-for-sanitizing-user-input-with-php) -and- [What are the best PHP input sanitizing functions?](http://stackoverflow.com/questions/3126072/what-are-the-best-php-input-sanitizing-functions) – mario Feb 10 '12 at 22:27
  • htmlspecialchars() is enough in the right context, but I think it's beter to sanitize it before outputing – Martin. Feb 10 '12 at 22:27