if you search for ‘ or ” and it breaks your software

, ,

Chances are if you are using a database and your application errors out when you enter ‘ or ” into a field and you get an error this usually means your prone to SQL injection. While SQL injection is very dangerous it’s relatively simple to resolve. Now I say its simple but it could mean lots of re-work for you.

I don’t want to talk about how to prevent and cure SQL injection. But, I want to show a solution to this problem. There are already so many great resources out there on how to resolve this issue.

Really the best quick thing you can do is escape all ” and ‘. PHP has a lot of really useful commands to carry out this like mysql_real_escape_string(deprecated) But, probably the biggest thing that can be done is to use PDO(PHP Data Objects).

 

This sample query

$sql = <<<SQL
SELECT * FROM users WHERE users.id = ‘123’;
SQL;

would turn into something like this

$sql = <<<SQL
SELECT * FROM users WHERE users.id = :user_id
SQL;
$sth = $dbh->prepare($sql);
$sth->execute([‘:user_id’ => ‘1234’]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC)

 

Some useful links:

  • http://php.net/manual/en/security.database.sql-injection.php
  • https://phpdelusions.net/pdo
  • https://www.w3schools.com/sql/sql_injection.asp

Implement dependency injection

Quick notes on implementing dependency injection

 

Most if not all PHP frameworks utilize dependency injection. Its allowing PHP to automate supplying function parameters. In my code example below in the class Test the function test requires the User class to be passed in as a parameter. Maybe you’ll want more things like Route or maybe some kind of Registry object. Having decency injection helps reduce redundant code by instantiating the function everywhere needed.

class user {
   public $id = 1;
}

class Test {
   public static function test( User $user ) {
      return $user->id;
   }
}

Here is a VERY basic example of how to implement PHP reflection.

$controller = Test;
$method = test;
$rm = new \ReflectionMethod($controller, $method);
$parameters = [];
foreach ($rm->getParameters() as $inc => $parameter) {
// Quick example getting the parameters and
// which class that parameter location is looking for
$class_name = $parameter->getType()->getName();
// Instatiate the new class
$parameters[] = new $class_name;
}
//Call the controller and method with the parameters you were expecting
call_user_func_array([$controller, $method], $parameters);

The idea is that PHP will use reflection to look at the method you are trying to call and figure out what parameters are expected. My example is simple, you can do a lot more. The idea is to present in note style form a starting point and to present the idea in a functional way.

 

Here are a few links for reference: