XSS is a big problem with a really simple solution. XSS stands for cross site scripting. Basically, someone attacking your application would try to save straight javascript into the database, for example:
<script>alert("I'm executable javascript lurking in your database")</script>
The reason this is bad is because when you retrieve that javascript from the database, it will add it to the page. Any time a browser sees a <script></script>, it automatically executes what's inbetween the script tags. The browser doesn't understand that this came from a user and not from a developer and it runs it as if it came from a developer.
So, how do we solve this problem? We basically change every < to &lt; in all data that is passed through to the query method.
Our first step we will update our bindValue code to include $this->xssFilter().
We want to change from
// $filter = $this->xssFilter($v);
$prep->bindValue($k, $v);
to
$prep->bindValue($k, $this->xssFilter($v) );
Within our db class we then add a method that helps us filter things named xssFilter().
Add this code between class db {...} in db.php, preferably at the bottom of the file.
private function xssFilter($value) {
return str_replace("<", "&lt;", $value);
}
What happens in the database when we filter less than signs?
This is before we started filtering:
+----+---------------------+------------------------------------+-----------+-----------+
| id | started | lastName | firstName | salary |
+----+---------------------+------------------------------------+-----------+-----------+
| 27 | 2020-02-26 16:18:05 | <script>alert('hi')</script> | Mogger | 50000.01 |
+----+---------------------+------------------------------------+-----------+-----------+
And this is after:
+----+---------------------+------------------------------------+-----------+-----------+
| id | started | lastName | firstName | salary |
+----+---------------------+------------------------------------+-----------+-----------+
| 28 | 2020-02-26 16:54:15 | &lt;script>alert('hi')&lt;/script> | Mogger | 50000.01 |
+----+---------------------+------------------------------------+-----------+-----------+
You should notice the &lt; html entity representation of the less than sign < which has replaced the original.
Basically, instead of getting this at the top of your page each time you reload the page:
You'll get this in your browser: