Page 1 of 1

how to block unwanted characters ( ;"%^&* etc)

Posted: Thu Apr 02, 2009 6:58 am
by eshban
hi,

On my server magic quotes are disabled by defualt. Now i want to block all invalid characters like ', ", %, &, # etc. Means if user enters them in a text box, then my query will not die.

Kindly help me that how can i do this.

Thanks

Re: how to block unwanted characters ( ;"%^&* etc)

Posted: Thu Apr 02, 2009 7:15 am
by Apollo
Good thing that your server has magic quotes disabled. It sucks :)

1. If you're using the submitted text in SQL queries, escape it with mysql_real_escape_string(). Not just to avoid errors on tricky chars, but also (especially) to avoid SQL injections.

2. If you're including the submitted text in your html output (or in pre-filled in form input fields, or whatever), convert it with htmlspecialchars().

Re: how to block unwanted characters ( ;"%^&* etc)

Posted: Thu Apr 02, 2009 7:27 am
by MasterBeta
You could use str_replace

Code: Select all

 
<?php
$test = $_POST['test'];
$badChars = array("'",'"','%','&','#');
$allowedChars = str_replace($badChars, "", $test);
echo $allowedChars;
?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" name="myForm" id="myForm">
<input name="test" type="text" /><input name="submit" type="submit" value="submit">
</form>
 

Re: how to block unwanted characters ( ;"%^&* etc)

Posted: Thu Apr 02, 2009 7:55 am
by Apollo
MasterBeta wrote:You could use str_replace
That's really a bad idea. What would happen if someone fills in his company name in some form: "Morgan & Co", you'd just wipe the "&" from the company name? (and much worse situations are possible)