Page 1 of 1

Help comparing values...

Posted: Sat Feb 28, 2009 6:38 pm
by Bruce Dickinson
Hello,

I'm trying to write a simple comment system on my web site and am having a little problem.

Obviously I don't want people to be able to post HTML tags as comments 'cause that could mess things up, so...

I'm trying to write code that stops this happening. What I'm trying to do is compare each element the $_POST['message'] variable (the comment) to the chars <, > and &.

At the moment, I'm only comparing it to < because I can't get it to work, here's what I've got so far:

Code: Select all

 
<?PHP
    session_start();
 
    $message = $_POST['message'];
    $length = strlen($message);
 
    for($i = 0; $i < $length; $i++)
    {
        if($message[$i] == '<')
        {
            echo("< found, comment not allowed...");
            break;  
        }
        else
        {
            echo ("comment OK");
            break;
        }
    }
?>
 
Well, as I said... that code isn't doing the job. I remembered running into this problem a long time ago when writing some C code, and the problem was solved by using the strcmp() function. That didn't seem to work for me in PHP, though, but I may have been using the function wrong.

Any help is much appreciated. :)

Re: Help comparing values...

Posted: Sat Feb 28, 2009 6:58 pm
by requinix
My policy is to let people type whatever they want but make sure they can't do any harm.

Ever heard of this function? It "converts" HTML into something safe.

Re: Help comparing values...

Posted: Sat Feb 28, 2009 7:09 pm
by Bruce Dickinson
That saved a lot of hassle :). Thanks for letting me know about that function, I won't forget it in future 8).