Quantcast
Viewing latest article 18
Browse Latest Browse All 27

Preventing SQL Injection | PHP Code For Beginners



If you are spent any serious time developing Web Application, you know the risk of SQL injection. Sql injection is caused when data is inserted into database that hasn’t been properly sanitized. For example, a simple demonstration of SQL injection would be an exploit that give a malicious person administration access to your site.

Say you have an HTML form that requires a username and password. Each of these form fields are named “user” and “pass”, respectively. On backend, the authentication mechanism checks the username and password against the database like this:
SELECT * FROM usertable WHERE username = ‘$user’ AND password = ‘$pass’;

If form data is unsanitized but the user actually inputs proper username and password, then the SQL query works and authentication is granted. However, if someone enters a more malicious string, they can wreak havoc on your system. For example, if user entered a username of user ’OR 1=1;-- and any password then SQL will also be valid and will give the user access to the protected system. The query would actually be run is shown here:
SELECT * FROM usertable WHERE username = ‘user’ OR 1=1;--random password

To understand the practical danger in this query, you have to understand that two dashes (--) is equivalent to the comment. Everything after he – is ignored by MySQL so it doesn’t matter if invalid password is provided. Also, because you haven’t “escaped” the single quote in the username, the single quote becomes the “end” of the value being checked against the username field. Though this is properly invalid as well, it doesn’t matter because the attack adds an OR 1=1 (which is always true) into the query. The query read, “Retrieve the record from usertable where username is ‘user’ or 1=1.” Because 1 is always equals to 1, the SQL always evaluates as true and attacker can access the protected resources or application.

To prevent against a possible SQL injection attack, the WordPress database class provides the $wpdb->prepare () method. It handles data sanitization of SQL statements to prevent against SQL injection,as show in below example. Note that instead of using %d to indicate a numerical replacement, you could use %1$d syntax to indicate, “replace this placeholder with the first replacement value in the format of a number.”

Using the prepare () method to sanitize SQL against SQL Injection attacks.
$sanitized_sql = $wpdb->prepare (“’INSERT INTO my_plugin_table SET field1 = %1$d, field2 = %2$s, field3 = %3$s’, 13, ‘Php code’, ‘Wordpress’);
$wpdb->query ($sanitized_sql);


Viewing latest article 18
Browse Latest Browse All 27

Trending Articles