PHP MySQL $_GET Hack prevention

Albert Renshaw picture Albert Renshaw · Dec 30, 2011 · Viewed 19.6k times · Source

Possible Duplicate:
Best way to stop SQL Injection in PHP

If I were to use the $_GET function to retrieve a variable from the URL how can I make it hack proof? Right now I just have addSlashes, what else should I add?

$variable1 = addslashes($_GET['variable1']);
//www.xxxxx.com/GetTest.php?variable1=xxxx

Answer

Mathieu Dumoulin picture Mathieu Dumoulin · Dec 30, 2011

The first and foremost rule with ANY input, not just $_GET but even with $_POST, $_FILES and anything you read from disk or from a stream you should always VALIDATE.

Now to answer your question in more details, you have several HACKS that exist in this world. Let me show you some:

XSS injections

If you accept data from the URL such as from the $_GET and output this data without stripping out possible tags, you might render your site prone to XSS injection or code injection. For example:

http://myhoturl.com/?search=<script>window.location.href="http://thisisahack.com/"</script>

This would output a hack to your site and people would be redirected to another page. This page could be a phishing attempt to steal credentials

SQL Injection

It is possible to inject SQL to your application. For example:

http://myhoturl.com/?search=%'; UPDATE users SET password=MD5('hello'); SELECT * FROM users WHERE username LIKE '%

Would make your SQL look like this:

SELECT * FROM articles WHERE title LIKE '%%'; UPDATE users SET password=MD5('hello'); SELECT * FROM users WHERE username LIKE '%%';

And thus you'd update all your user's password to Hello and then return something that doesn't match.

This is only a brief overview of what you can do with SQL injection. To protect yourself, use mysql_real_escape_string or PDO or any good DB abstraction layer.

Code injection

Lots of people like to include data from somewhere on the disk and allow uploads of files. For example:

//File igotuploaded.txt
<?php echo 'helloworld'; ?>

And the url allows you to INCLUDE a file by name. ?show=myhotfile.txt

//In this file we include myhotfile.txt
include($_GET['show']);

The person changes that to ?show=../uploads/igotuploaded.txt and you will run echo 'Hello world';

That is dangerous.

rule of thumb... NEVER TRUST USER INPUT, always validate, prevent, validate, fix, validate and again correct...

Good luck