SQLite Injection
If your site allows users to enter input through a web page and inserts that input into a SQLite database, then you face a security problem known as SQL injection. This chapter will explain how to prevent this from happening and keep your scripts and SQLite statements safe.
Injection usually occurs when you request input from a user, such as asking the user to enter a name, but the user enters a SQLite statement instead, and that statement will then run on the database without your knowledge.
Never trust data provided by users, so only process validated data; this rule is accomplished through pattern matching. In the following example, the username is restricted to alphanumeric characters or underscores, and its length must be between 8 and 20 characters - please modify these rules as needed.
if (preg_match("/^\w{8,20}$/", $_GET['username'], $matches)){
$db = new SQLiteDatabase('filename');
$result = @$db->query("SELECT * FROM users WHERE username=$matches[0]");
}else{
echo "username not accepted";
}
To demonstrate the problem, consider this excerpt: To demonstrate the problem, consider this excerpt:
$name = "Qadir'; DELETE FROM users;";
@$db->query("SELECT * FROM users WHERE username='{$name}'");
The function call is used to retrieve records from the users table where the name column matches the name specified by the user. Normally,$name contains only alphanumeric characters or spaces, such as the string ilia. But here, an entirely new query has been appended to $name, and this call to the database will cause catastrophic problems: the injected DELETE query will delete all records in users.
Although there are database interfaces that do not allow query stacking or executing multiple queries in a single function call (if you try to stack queries, the call will fail), SQLite and PostgreSQL still perform stacked queries, that is, execute all queries provided in one string, which causes serious security problems.
Preventing SQL Injection
In scripting languages such as PERL and PHP, you can skillfully handle all escape characters. The programming language PHP provides the string function SQLite3::escapeString($string) and sqlite_escape_string() to escape input characters that are special for SQLite.
Note: Using the function sqlite_escape_string() requires a PHP version of PHP 5 < 5.4.0。
PHP 5 >= 5.3.0, PHP 7 and above use the following functions:
SQLite3::escapeString($string);//$string为要转义的字符串
The following methods are not supported in the latest versions of PHP:
if (get_magic_quotes_gpc())
{
$name = sqlite_escape_string($name);
}
$result = @$db->query("SELECT * FROM users WHERE username='{$name}'");
Although encoding makes inserting data safe, it presents simple text comparisons; for columns containing binary data in a query, theLIKE clause is unusable.
Note that addslashes() should not be used to quote strings in SQLite queries, as it will cause strange results when retrieving data.