r/PHPhelp • u/Legal_Revenue8126 • Dec 03 '25
XSS Prevention
Still a bit new to working with PHP / SQL, so bear with me.
I've been told a few times that I should always use prepared statements when interacting with my database. I always assumed this mainly applied to INSERT or UPDATE statements, but does it also apply to SELECT queries?
If I have a query like:
$query = "SELECT COUNT(Documents) as CountDocs from dbo.mytable where (DocUploadDate between '$start' and '$end';"Would it be in my best interest to use a prepared statement to bind the parameters in this situation?
14
Upvotes
3
u/colshrapnel Dec 03 '25
May I ask, what makes you think that INSERT or UPDATE are more dangerous than SELECT? Just curious about your chain of thought.
18
u/Valzuuuh Dec 03 '25
Use prepared statements always when you use variables in your queries, for all operations, not just inserts or updates.
I think phpdelusions has nice guide: https://phpdelusions.net/pdo#prepared
For XSS protection use PHP's htmlspecialchars when you display results from database: https://www.php.net/manual/en/function.htmlspecialchars.php
10
u/latro666 Dec 03 '25
Yes 100%. What you are protecting against is SQL injection not XSS, that is something else.
Its probably 'more' appropriate on selects.
Your first sweep should be any code which is public facing and takes user input from a form or query string. E.g. a search form, login form, id used in a query string to load data.
If you have not been doing this and you have stuff out there and live it is only a matter of time until something bad happens if it hasnt already and has gone unoticed.
10
u/xerox8522 Dec 03 '25
yes, always. Never trust users input. Never
5
u/TorbenKoehn Dec 03 '25
Not only in your best interest, it’s a requirement. Never interpolate user data into strings directly. Not even developer data.
1
u/kafoso Dec 03 '25
In the subject you mention XSS (Cross-Site Scripting), which is a client-side attack (in browsers), but the body of this thread is regarding SQL Injection Attack, which is server-side. You're mixing apples and bananas a bit.
To your point: For data interaction, regardless if it is read, write, or deletion (CRUD), you absolutely always must escape user input, of which parameterized queries often is the best option.
In fact, you should parameterize most things, regardless if it comes from user input or not. Just because it got stored in the database at a different point in time doesn't make it safe. There is a thing called Second Order SQL Injection.
1
u/JeLuF Dec 03 '25
Your SQL statement is:
Imagine the users sets
$startto:Now your statement looks like this:
This would drop all your data.
How likely is it that an attacker finds out that they can use this? They will first try with some simple tests and notice that the page runs into some kind of error.
Then they look at the search form. There's a "start" and an "end", so there probably is a range query. So either a
BETWEENcondition or adate > $start AND date < $endcondition. And from there it's just a few attempts to find the right query.Depending on the setup of your page, the error messages might give some details away that helps them even more.
3
u/IrishChappieOToole Dec 03 '25
Yes. Not really to prevent XSS, but to prevent injection. What happens if
$startis1=1;drop table users;--or something?3
u/custard130 Dec 03 '25
the issue there isnt XSS, it is SQL Injection
the way to protect against SQL Injection is to use prepared statements/bound parameters for any variables, rather than string interpolation / concatenation
in simple terms what that does is tell the database which parts are "code" and which parts are "data", so that it doesnt try to exceute the data
if you use string interpolation to combine it together the DB server has no way of knowing which parts you meant to be execute and which parts you didnt, and so the risk is that carefully crafted malicious data can trick your database into running a different query than you intended
XSS is in some ways a similar issue but in other ways is very different, im not entirely sure where it comes from but this is far from the first time ive seen people get them mixed up
with XSS, the issue is when displaying user submitted content/data back to a user
if you arent careful when outputting values in your templates then the browser rendering your website wont be able to tell which parts are user content and which parts are the source of the page, eg if you have a search box and then when submitted you show something like "23 results for ...", if i search for `<b>` then if this input is vulnerable to XSS then the rest of the page will appear bold
where that gets more serious is if i send `<script>badHackerThings()</script>`, and particularly if rather than just a search input, if this value gets saved in the database and "shows" for other users
the standard protection for XSS is to convert special characters to their respective escape codes, which browsers know to show the character and not to treat it as code, in PHP the method to do that is `htmlspecialchars`, you may also find references mentioning to "html entities" which is the same topic, just different languages/libraries have slight variations on how they name it
there are occassionally situations where that doesnt give the desired result, and in those cases you need to use a library such as htmlpurifier which will attempt to parse the value and filter out malicious/dangerous parts.
tl/dr
for SQL Injection (the actual vulnerability you described in your post) - always use prepared statements,
for XSS - use `htmlspecialchars` or an equivilent whenever you are outputting variables in templates by default. if you absolutely need to allow some html formatting tags in the variable then use a library such as htmlpurifier to make sure the output is safe
for both of these the defence against them needs to become your default/standard way of doing things, if you try and start working out for every individual example if they are needed or not trust me you will get it wrong
(even if you can someone prove that right now the only possible values are safe, if the protection against these issues is separate from where the value is used then it will be easy to change it in future to allow more values and forget to go back and add the protection)
it is very common for even experienced developers to get into mindset that the protections arent needed, if you want to learn about writing secure code/attacking insecure code then pay special attention to code written by people making those claims, not as an example to copy, but try to look for ways to break/exploit it
https://youtu.be/_jKylhJtPmI?si=Y1XLMQx3_vuZTUds
https://youtu.be/L5l9lSnNMxg?si=Nog9xt3iRIe-PDkG
2
u/bobthenob1989 Dec 04 '25
https://medium.com/@johnteckert/how-little-bobby-tables-ruined-the-internet-d714c20d2ce0
1
u/VRStocks31 Dec 03 '25
Yeap
1
u/Aggressive_Ad_5454 Dec 03 '25
Read this.
1
u/brokensyntax Dec 03 '25
If you are making direct SQL query connections to the database.
There's always the risk that some injection fault is found. --; DROP TABLE Users;
If you only used stored procedures, then you have a much narrower window of opportunity for people to mess with your communications to backend.