Joel
Joel

Reputation: 6107

RegEx to avoid user input injection

Upon receiving an input from a user, I am doing the following on my server (with PHP):

$safe_input = ereg_replace("[^A-Za-z0-9-]", "", $_GET["input"]); 

Then I am using the $safe_input variable for SQL queries and also printing it to the user's screen.

Does that guarantee that no injection of any sort (SQL injection, XSS, etc.) is possible?

Thanks,

Joel

Upvotes: 0

Views: 1707

Answers (2)

rvxnet
rvxnet

Reputation: 457

Well, what it does is ensure that you're only allowing A-Z (upper or lower), numerics, and the "-" dash character in your $safe_input string.

In theory, your SQL could still be munged by someone adding "--" to an input in order force the latter part of the statement to be treated as an SQL comment.

Something as simple as what you've posted is not a solution to malicious code injection - and will most likely cause you issues down the line when you want to allow a user to send characters other than the ones you've explicitly allowed.

You should look at 3rd party PHP libraries that specifically deal with this kind of thing - there are plenty out there for SQL and XSS prevention. Or even look at the server level and think about adding one of the Apache modules available for this task (providing you're using Apache of course...). By going down this route you'll be taking a much more holistic approach to protection - and you'll be leveraging expertise in this area, rather than trying to re-invent this particular wheel for your project.

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382726

First of all ereg family of functions is deprecated, you should use preg family of functions instead:


Don't limit users to just A-Za-z0-9-. I would suggest you to go for:

HTML Purifier is a standards-compliant HTML filter library written in PHP. HTML Purifier will not only remove all malicious code (better known as XSS) with a thoroughly audited,
secure yet permissive whitelist, it will also make sure your documents are standards compliant, something only achievable with a comprehensive knowledge of W3C's specifications.

You can customize as to what is accepted and what is rejected.


Interesting:

It is interesting to note that Kohana the improved alternative of CodeIgniter also supports HTML Purifier for security.


As for SQL injection, the least you can do is to use mysql_real_escape_string function. The better way is to use prepared statements though.

Upvotes: 1

Related Questions