I'm currently working with php standard library functions to sanitize string inputs for mysql_query function (not just stripslashes and mysql_client_encoding but checking consistency of the whole query, including validating some critical field values and checking some table access restrictions)
I've been told that using development frameworks / extension libraries like CakePHP or PEAR could make my life easier when facing this issues on any of my projects, no matter how small.
From my point of view when doing small simple projects anything added to the standard libraries can be tricky to work with and usually isn't worth the effort, but I'm really eager to explore what alternatives to code everything from scratch are out there.
Any suggestions on where or what to start with?
PHP's PDO handles all sanitation with prepared queries. It's already written for you and included by default in PHP >= 5.1. Plus it's compatible with a bunch of DB engines (MySQL, MsSQL, Oracle, PostgreSQL, SQLite, and more) and adds support for transactions.
//Works for
$id = 23;
$id = 'harmless string';
$id = '0 OR WHERE 1 = 1 --';
$pdo = new PDO('mysql:host=localhost', $username, $password);
$stmt = $pdo->prepare('SELECT title, body FROM posts WHERE id = :id');
$stmt->execute(array(
':id' => $id // Automatically handles sanitizing
));
$results = $stmt->fetchAll();
If you're not doing it already, at a minimum, consider using one of the database extensions like PDO instead of mysql_query()
and all that. If you use them correctly, they have some very nice features, such as query sanitizing to thwart SQL injection without having to remember to run mysql_real_escape_string()
.