How to filter & escape data from Injection attacks in PHP!
Ask any security expert! He will say you should always filter POST and GET data by escaping them before insertion into the database. In that way your scripts can be safe from SQL injection attacks.Many php programmers are so lazy and just directly insert the POST data without filtering it like
1
| mysql_query( "INSERT into `users` (`name`,`email`) VALUES ('$_POST[name]','$_POST[email]')" ): |
A very good way to clean user input is using mysql_real_escape_function() which is a good way to protect from SQL injection attacks. You can use the function like this.
1
2
3
| <? $name = mysql_real_escape_string( $_POST [ 'name' ]); ?> |
I was after a few lines of code where the server would automatically escape/filter POST data before inserting into database. It turns out that mysql_add_slashes() does the job but it causes more problems than anything and it is not advisable to use this function and it has been discontinued since PHP 6.0
Below is the nice little function that would filter/clean all user input and offers protection from
1. MySQL Injection attacks by escaping data.
2. Protection from XSS attacks through script tags.
01
02
03
04
05
06
07
08
09
10
| function filter( $data ) { $data = trim(htmlentities( strip_tags ( $data ))); if (get_magic_quotes_gpc()) $data = stripslashes ( $data ); $data = mysql_real_escape_string( $data ); return $data ; } |
1
2
3
| foreach ( $_POST as $key => $value ) { $mydata [ $key ] = filter( $value ); } |
1
| mysql_query( "INSERT into `users` (`name`,`email`) VALUES ('$mydata[name]','$mydata[email]')" ): |
No comments:
Post a Comment