Reputation: 1
I'm pretty new to PHP & SQL security and I was thinking about a solution for validating / filtering user input.
As far as I understand you have to mainly worry about 2 things:
(1) somebody injecting SQL queries into input fields that interact with a database
(2) somebody putting stuff like <script>
tags inside their input which is then printed to the page again
While researching I found the following solutions:
For (1): prepared statements
For (2): validating / filtering HTML-tags
I know that you have to validate / filter any user input and as far as I understand most security leaks exist because of mistakes doing so.
For example simply filtering out the <script>
tag in the following input:
email@<sc<script>ript>example.com
So what about a really simple algorithm rejecting any user input containing "<" or ">" (assuming there is no reason for users to use those symbols) and to replace something like [b]
inside user input with <b>
to allow specific tags? Isn't this a bulletproof approach to prevent malicious HTML content or what do I miss?
Also I'd like to know if using prepared statements all the time makes SQL injection impossible or is it still possible to do SQL injection on pages that exclusively use prepared statements?
Upvotes: 0
Views: 284
Reputation: 16113
You could do that, yes. But then you might be open to another attack. And you could fix that, but then you might still...
Because of that it's easier to whitelist. There are only certain characters allowed (though a more broad charset is being allowed), you can simple allow just those.
The basic logic would be that a email only contains a-z
0-9
-
_
.
and @
. If any character outside that set is used, its wrong.
From there, you could specify it more. An email is that set of characters(minus @), than the @
, then that charset(minus @).
From there, you could add a domain check, eg \.{2,}$
(must end with dot and at least to letters).
From there...
And that is just the saving part. On display, you need all kinds of tricks to make sure it's not XSS.
Or you could just use
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Not an emailaddress, please try again before submitting!";
}
Upvotes: 0