Skip to content


Protect your data from user input

I came to a point where I needed to filter the user input (not just tell the user something like : “The username isn’t in the right format” or “Please choose a valid name for your username”), I mean let him to input in the form anything he wanted too but in the end what we store in the database is his processed input (only A-Z, a-z and 0-9).
I had the Visual Basic and C++ thinking .. I must do that and that and that to get rid of unwanted characters. It was a little time consuming and I was in hurry so I googled and I reached the ereg_replace help page on PHP.net website. Suddenly all became much much easier :D , just write a regular expression (ohh, by the way .. if someone asks I can write a small tutorial on regular expressions) like this : “[^A-Za-z0-9]” and that was it :) .

Below is a small example on how to filter (remove all characters except uppercase/lowercase letters and numbers)

  1. <?php
  2. //our string
  3. $str = "nek#$#hbet|20&&07";
  4. $filtered = ereg_replace("[^A-Za-z0-9]", "", $str);
  5. print $filtered; // will print ‘nekhbet2007′
  6. ?>

PHP is a strong language with a lot of functions that help us to decrease the development time. So before thinking how to do a certain thing just take a look first at www.php.net and see if what you need isn’t already done :)

Posted in PHP Tips & Tricks.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.


Get Adobe Flash playerPlugin by wpburn.com wordpress themes