cleaning up text entered in a form

Discussion in 'PHP' started by Rasputin, Aug 8, 2009.

  1. #1
    I have a function that is supposed to make text entered in a form safe before it gets posted in a database - is it good enough? does it cover all the security possibilities? Is there a better way of doing the same? Thanks!

    function cleanText($textstring, $stringLength) {
    
    $cleanString = nl2br($textstring);
    $cleanString = strip_tags($cleanString,"<b><p><br>");
    $cleanString = trim ($cleanString);
    $cleanString = mysql_real_escape_string($cleanString);
    if(strlen($cleanString)>$stringlength) $cleanString=substr($cleanString,0,$stringLength);
    
    return $cleanString;
    }
    Code (markup):

     
    Rasputin, Aug 8, 2009 IP
  2. premiumscripts

    premiumscripts Peon

    Messages:
    1,062
    Likes Received:
    48
    Best Answers:
    0
    Trophy Points:
    0
    #2
    mysql_real_escape_string is supposed to be the last thing you do. Yet you do it before you do the possible substr. So that could introduce a vulnerability (or at least incorrect SQL generation)

    Also, you're doing strip tags but allowing <p> etc.. This means you probably aren't doing htmlspecialchars on the output page? Again vulnerable since people could write <p onhover="javascript:..">etc</p>

    You should probably use something like htmlpurifier.org instead. Or if that's overkill, some regexes could do the trick as well.
     
    premiumscripts, Aug 8, 2009 IP
    Rasputin likes this.
  3. Rasputin

    Rasputin Peon

    Messages:
    1,511
    Likes Received:
    67
    Best Answers:
    0
    Trophy Points:
    0
    #3
    sounds like some good advice, I'll take a look at htmlpurifier

    thanks!
     
    Rasputin, Aug 8, 2009 IP
  4. StewieGriffin

    StewieGriffin Peon

    Messages:
    81
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #4
    You current function looks good.You might be interested in having a look at this.
     
    StewieGriffin, Aug 8, 2009 IP