HomePHP Page 4 - PHP Programs to Prevent MySQL Injection or HTML Form Abuse
Validating Text and Email Input - PHP
It has been known for a while that if a form is unsecured, malicious code in the form of a MySQL injection will be initiated to attack the site. HTML forms such as drop down menus, search boxes and check boxes are all susceptible entry points for this type of abuse. This article will explain what happens in this kind of attack, and how to prevent it.
This will be used to validate form input such as a username, first name and last name of the person, as well as the email address.
//Validate text input
if (! preg_match('/^[-a-z.-@,'s]*$/i',$_POST['name']))
The good thing about this validation script is that it will not accept blank input. Some malicious users also manipulate database by entering a blank input. In the above script, it validates only one text variable, “$name.” This means that if you have three text variables, you can make three validating scripts for each of those variables, to make sure every variable is clean before it goes into the database.
Want stronger protection?
If you need stronger protection you can validate the user input using the above scripts andmysql_real_escape_string; this will offer secondary protection in case the above validation scripts fail due to some reason. Discussing this feature is beyond the scope of this article and you can read useful resources on:http://www.php.net/mysql_real_escape_string
However, before you can use this feature, you must be connected to a MySQL database, or else it will return an error. Some really talented hackers can play around with mysql_real_escape_string, which is why it is highly recommended to have a double filter in your scripts (validating scripts +mysql_real_escape_string) to make hacking much more difficult.