php – stop HTML/Javascript and SQL injection on website-ThrowExceptions

Exception or error:

I own an online game where you have a status box. Which you can update it on how you’re feeling. The problem I have had was that users were putting java script tags into messages and into status. So when another user came to their page, a pop up box would pop up saying haha or whatever they wanted.

I then stopped that by using

$status = mysql_real_escape_string($_POST['status']);
$foo = preg_replace('/[^a-z]/i', null, $status );

That has now stopped any JavaScript being ran but now when someone sends someone a message, it takes the spaces out so for the message “how are you ” It will show “howareyou”. Of course this is safe but users can’t read messeges. Is there any other way from stopping script tags being inserted into the virable but still allow spaces?

I’m also real scared of someone hacking me with XSS. Because before, I was told a user could enter something in a message then when the other user opens it, it will send them there password…..

How to solve:

First of all using mysql_real_escape_string() on all external input prevents all SQL injections – no preg_replace needed at all! But that’s only for preventing SQL injection.

In order to prevent scripting / HTML injection on your website, you should always use htmlspecialchars() to escape all text that comes from user input before you present it to a visitor of your site. (e.g. immediately after SELECT from database)

Please take this serious: If you find the time, go and google for SQL injection! It is not complicated and you’ll understand it easily. If you create websites – no matter for whom – and store user input in a database, you will observe that someone tries to do SQL injection. It is easy to do, and there is automated software out in the web that can easily try all sorts of SQL injection on hundreds or thousands of websites automatically! And for a client it definitely is not acceptable if the developer doesn’t prevent SQL injection at all, so take your time for this issue.

The same goes for script injection! As with SQL injection, preventing this is really very easy. All you have to do is convert all text that comes from user input into HTML, so that when some evil guy enters <script>...</script>, your visitors will simply see exactly this, because for example the < gets converted into &lt; and thus prevents the script from being interpreted by the browser as javascript.


$foo = htmlspecialchars($status);

Leave a Reply

Your email address will not be published. Required fields are marked *