Software Development

Starting to stop SQL-injections

In a lot of PHP-examples strings are concatenated before a database query is being executed as below. Some examples advise to use PHP-functions mysql_real_escape_string() and/or addslashes() to make database query safe against SQL-injections. But this isn’t really a solution as when using addslashes() also requires the use of stripslashes() after retrieving data from a database. Some sites show the lack of proper implementation and show the famous \’ string on a website.

$sth = $dbh->prepare('select userid from accounts where username = "'.$form_username.'"');

Like in Perl with DBI, also PHP has PDO that allows for variables to be parameterized while executing a query as in the example below. This removes the need for homemade solutions that don’t cover all use-cases and allows for a way to provide a stable and more secure interface for your applications when communicating with databases.

$sth = $dbh->prepare('select userid from accounts where username = ?');

This doesn’t stop the need for sanitizing variables like with input from users.

Software Development

Cleaning input enough?

Input validation is a known issue, but writing some PHP-code today let me write the following and I’m wondering if I forgot something. It is only to make sure no cleansed variable will enter a switch statement for example.

  if (isset(_POST['action']))
    if (strlen(preg_replace("/[^a-zA-Z0-9-]/i","",_POST['action'])) == 0)
      page_action =_POST['action'];
      page_action = '';
  elsepage_action = '';

  switch ($page_action) {

For now, I need to check the code that no $_POST variable is entering the code unchecked before I put the code online. This also includes variables for SQL-statements to eliminate SQL-injections.