I am trying to figure out a way to sanitize input going into sqlite from php. I cannot use mysql. Is it enough to simply use sqlite_escape_string or do I need to do anything else? Also I can only use sqlite2.
5 Answers
The best way to avoid SQL injection is to enforce the use of parametric queries, and never ever manually assemble SQL statements by string concatenation or variable interpolation.
On PHP 5+, you may use PDO, which is a multi-database abstraction layer supporting (among others) SQLite, and parametric queries.

- 7,964
- 3
- 27
- 40
Escape functions make sure that the special characters (quotes mainly) that are used by the SQL dialect are escaped, so that your inserts/updates etc work. All sqlite_escape_string does is escape single quotes.
Then there is the substantial concern that someone can craft an SQL injection. Because you're using v2, you can't use the prepare and _bind() functions that would protect you.
SQLite lets you chain commands seperated by ';' so there is an issue there. I would suggest you start by carefully crafting your parameters using either helper functions you write or using sprintf and insure that you are typing your ints, floats, and strings appropriately.
You should be able to create your own escape function that "escapes" things you want to watch out for... most specifically the semicolon, using the ... ESCAPE '\' at the end of your queries, assuming you utilize the backslash as your escape character.
Then you have the issue of someone intentionally inserting malicious content (XSS). Grigor provided one solution -- use htmlentities() on your strings.

- 14,876
- 3
- 46
- 51
There are ways, but it depends on the target of your input, Please refer to this question to understand it better: What's the best method for sanitizing user input with PHP?

- 1
- 1

- 172,118
- 50
- 264
- 308
sqlite_escape_string()
should do all the sanitizing you need to input the string. As for outputting it, if it's being outputted into HTML, then use htmlspecialcharts()
on it before outputting it.

- 8,220
- 3
- 24
- 30
SQLite offers sqlite_escape_string()
for that. It's only available for PHP 5, though.
Solely relying on these methods will not save you from injections, though. An imperative measure is to always validate user-provided input first, before subjecting it to methods, you have to rely on - but actually haven't authored.

- 33,871
- 11
- 91
- 99