1

Is it a good idea to use:

// input can only contain numbers letters
if (preg_match('/^[a-zA-Z0-9_\-\.]+$/', 'input')) {}

Will this help preventing SQL injections ? and make site more secure?

1 Answer 1

1

I will begin by saying that you absolutely should be using PHP Prepared Statements here. Do not try to handle SQL injection yourself, and besides this problem was solved a long time ago.

Your pattern might block certain types of SQL injection. For example, let's say you had the following SQL query:

SELECT col1, col2 FROM some_table WHERE col = ?;

Your regex pattern would prevent someone from injecting 'value'; DELETE FROM some_table into the query. This is because your regex pattern doesn't allow for semicolon.

However, there are other types of injection attacks which don't involve chaining on additional (malicious) statement. Union attacks can also happen, and your current regex does allow for this. Consider injecting the following fragment:

'value' UNION ALL SELECT username, password FROM users

This would give the following full SQL query:

SELECT col1, col2 FROM some_table WHERE col = 'value'
UNION ALL
SELECT username, password FROM users;

While it would probably be unlikely that the attacker would be able to pull this off, it could happen, and if it did, the attacker could get every username and password from a totally different user table.

Use prepared statements and forget about handling this problem yourself.

Sign up to request clarification or add additional context in comments.

2 Comments

i am using prepared statements, but i want more security and perfection for my web app.
Statements are as good as you will get. If they aren't secure enough, you have some other (bigger) problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.