Forum Moderators: coopster

Message Too Old, No Replies

fix harmful code from input forms

htmlspecialchars

         

Snurk

8:25 pm on Sep 7, 2005 (gmt 0)

10+ Year Member



Hi everyone!

I'd like to hear what kind of protection you use for making sure users input valid data into forms, and dont input ' (quote) " (doublequote) etc.

I have tried to do a str_replace, but with little success:

function remove_harmful_code($variable){
$variable = str_replace("'", "'", $variable);
$variable = str_replace('"', """, $variable);
return $variable;
}

I get the same results if using htmlspecialchars, it simply doesnt replace the " and the '....

Any help is appreciated! :-)

StupidScript

2:38 am on Sep 8, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



For those instances, use
addslashes()
.

Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

PHP Manual - addslashes() [php.net]

i.e.

$user_input=addslashes($_POST["user_comment"]);

To use

str_replace()
to swap quotes for apostrophes you'll need
$user_input=str_replace("\"","'",$_POST["user_comment"]);

or similar. Results in:
Before:
I said, "You love it!"

After:
I said, 'You love it!'

To use

str_replace()
to keep existing quotes you'll need
$user_input=str_replace("\"","\\\"",$_POST["user_comment"]);

or similar. Results in:

Before:
I said, "You love it!"

After:
I said, \"You love it!\"

To use

htmlspecialchars()
to change any HTML special character into its equivalent HTML syntax you'd do
$user_input=htmlspecialchars($_POST["user_comment"]);

or similar.

Before:
I said, "You love it!"

After:
I said, "You love it!"

To use

htmlentities()
to change any HTML entity into its equivalent HTML syntax you'd do
$user_input=htmlentities($_POST["user_comment"]);

or similar.

Before:
I said, "You love it!"

After (oddly):
I said, "You love it!"

BananaFish

4:02 am on Sep 8, 2005 (gmt 0)

10+ Year Member



The basic principle of filtering is not to filter out what is "bad" but to only allow what is "good". EG:


foreach($_POST as $k => $v){
${$k}=preg_replace("/[^a-z0-9\s.!_@-]/i","",$v);
}

Where the stuff inside your reg exp is what you allow.