I am wondering what's the easiest method to celar input data before placing it right into a mysql database. You will find lots of function: trim(), addslashes, mysql_real_escape_string and so forth. Now i am by using this simple function:

    function filter($var){

        $data = preg_replace('/[^a-zA-Z0-9]/','',$var);

        $data = trim(addslashes($data));

        return $data;

    }

What's the easiest method to get it done? Thanks

to become safe and sound, when confronted with mysql, mysql_real_escape_string() -- always employ this. always.

It is best to have a look at prepared statements that virtually safeguard you from all type of SQL Injection.

The parameters to prepared claims don't have to be cited the motive force instantly handles this. If the application solely uses prepared claims, the developer can be certain that no SQL injection will occur (however, if other servings of the query are now being developed with unescaped input, SQL injection continues to be possible).

Using mysql_real_escape_string() is sufficient for security reasons. A different way to get it done is applying prepared claims.

But you can examine what information with what type you would like inside your database. You will find several functions and language constructs you could utilize: Typecasts, filter_*() functions, int_val(), abs(), trim(), far more more.

The very best factor would be to do multiple things:

  1. Validate data
  2. Clean data
  3. escape date

The validation would be to check if the data you have makes sense at all. For example should you expect a date of birth you check if the format is correct and even perhaps if the date amkes sense. This not just has security benefits but additionally prevents some (not every) errors of wrong data. The various tools there rely on the situation, regular expression (preg_match) are frequently the ideal choice.

Cleaning information is frequently not necessarily needed, but nice, for example if your user types in certain value use trim() to separate of some whitespaces, which can be mistakes from copy or such. It has no security benefit but enhances the general quality of the data. That is good.

These two things ought to be done at the start of your script. While "early" is dependent in your achitecture. Sometimes it seems sensible to wash first an validate then or doing the work at the same time (preg_replace)

When delivering data of to some database or putting it in HTML or these things oyu need to escape it accordingly somewhere you're using. You want to do that for those data, even if you verfied the format in advance to become safe and sound. When speaking to mysql fundamental essentials real_escape_string functions for example, for HTML it's htmlentities() or htmlspecialchars(). with databases it's also advisable too consider prepared claims, either PDO->prepare + execute() or mysqli->prepare() +execute()