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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
eshban
Forum Contributor
Posts: 184
Joined: Mon Sep 05, 2005 1:38 am

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

Post 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
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

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

Post 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().
MasterBeta
Forum Commoner
Posts: 38
Joined: Thu Apr 02, 2009 4:35 am
Location: Lincoln, NE

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

Post 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>
 
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

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

Post 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)
Post Reply