You've got two options - escaping the special characters in your
unsafe_variable, or using a parameterized query. Both would protect you from SQL injection. The parameterized query is considered the better practice, but escaping characters in your variable will require fewer changes.
We'll do the simpler string escaping one first.
//Connect
$unsafe_variable = $_POST["user-input"];
$safe_variable = mysql_real_escape_string($unsafe_variable);
mysql_query("INSERT INTO table (column) VALUES ('" . $safe_variable . "')");
//Disconnect
See also, the details of the
mysql_real_escape_string function.Warning:
As of PHP 5.5.0
mysql_real_escape_string and the mysql extension are deprecated.
As of PHP 7.0.0
mysql_real_escape_string and the mysql extension have been removed.
Please use
mysqli extension and mysqli::escape_string function instead
To use the parameterized query, you need to use MySQLi rather than the MySQL functions. To rewrite your example, we would need something like the following.
<?php
$mysqli = new mysqli("server", "username", "password", "database_name");
// TODO - Check that connection was successful.
$unsafe_variable = $_POST["user-input"];
$stmt = $mysqli->prepare("INSERT INTO table (column) VALUES (?)");
// TODO check that $stmt creation succeeded
// "s" means the database expects a string
$stmt->bind_param("s", $unsafe_variable);
$stmt->execute();
$stmt->close();
$mysqli->close();
?>
The key function you'll want to read up on there would be
mysqli::prepare.
Also, as others have suggested, you may find it useful/easier to step up a layer of abstraction with something like PDO.
Please note that the case you asked about is a fairly simple one, and that more complex cases may require more complex approaches. In particular:
- If you want to alter the structure of the SQL based on user input, parameterised queries are not going to help, and the escaping required is not covered by
mysql_real_escape_string. In this kind of case you would be better off passing the user's input through a whitelist to ensure only 'safe' values are allowed through. - If you use integers from user input in a condition and take the
mysql_real_escape_stringapproach, you will suffer from the problem described by Polynomial in the comments below. This case is trickier because integers would not be surrounded by quotes, so you could deal with by validating that the user input contains only digits. - There are likely other cases I'm not aware of. You might findhttp://webappsec.org/projects/articles/091007.txt a useful resource on some of the more subtle problems you can encounter.
No comments:
Post a Comment