Sadly my student website just got hacked. Someone insert script tag
and stored in the database. Database also been published in a website call pastebin. I just took down the website. Can someone show me how to fix this quick.
Asked
Active
Viewed 118 times
-1

schoolteacher
- 36
- 7
-
take a look at magic quotes and `mysqli_real_escape_string` – Saurabh Aug 11 '16 at 09:11
-
3Use prepared statement with bind parameters when inserting data and htmlentities on any user generated data before outputting it – rypskar Aug 11 '16 at 09:20
-
1Escape all the data you output to a web-browser by using [htmlspecialchars](http://php.net/manual/en/function.htmlspecialchars.php). That way it never gets executed when sent to the web-browser. – Ryan Vincent Aug 12 '16 at 04:20
-
1Yes, the data will be stored. If you don't want the 'script' tags to be stored then you will have to filter them out. But it isn't important to do that as long as you **escape all the output that you send to the web-browser** as it will not be executed. You will just see it as text. – Ryan Vincent Aug 12 '16 at 05:01
-
1If the fields in your form are expected to contain known things such as email, post codes, fone numbers etc. then always validate them. The issue is with comments and free text fields. – Ryan Vincent Aug 12 '16 at 05:07
2 Answers
1
You can use strip_tags() before inserting any value into database to remove any HTML or PHP tags from the string.
This is how you can remove HTML and PHP tags from string,
$code=strip_tags($code);
Use it with every variable you want to insert into database.
$code=strip_tags($code);
$fn=strip_tags($fn);
$em=strip_tags($em);
$un=strip_tags($un);
$hash=strip_tags($hash);
$salt=strip_tags($salt);
$ip=strip_tags($ip);
$this->db1->query("INSERT INTO users SET code='" . $code . "', firstname='" . $fn . "', email='" . $em . "', username='" . $un . "', password='" . $hash . "', salt='" . $salt . "', registerdate='" . time() . "', ipregister='" . $ip . "'");
Although strip_tags() doesn't prevent SQL injection completely. You should better use prepared statements.
Reference: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

Alok Patel
- 7,842
- 5
- 31
- 47
-
thanks, can you show me the completed code of this. i try doesn't work! – schoolteacher Aug 11 '16 at 09:18
-
You just have to call `strip_tags` on each variable and then use it in the query string. Check my updated answer. – Alok Patel Aug 11 '16 at 09:22
-
3
-
That's true. Better to use prepared statements to prevent SQL injection. Added in the answer, Thanks. – Alok Patel Aug 12 '16 at 03:31
1
Use a combination of filters and prepared statements.
http://php.net/manual/en/function.filter-input.php
http://php.net/manual/en/pdo.prepared-statements.php