What Is And How To Prevent Url Injections In Php?
Basically url injections is someone who tries to manipulate your database using the url.
For instance if your url is www.domain.com/index.php?id=1
Somewhere in the php of the site will be a section which calls the id and inputs it into the database to get the results needed for the string provided.
for instance a bad coder would make this string vulnerable to the database by doing this.
$id = $_GET["id"]; sql = "SELECT * FROM databasetable WHERE id='$id'";
which means its dragging anything that is put into the url and inputting it into the database!
Even a novice hacker could get into your server and get to all the websites, users and passwords stored within the server,
database with this code.
A lot of people are stating that all you need to do is use the mysql_real_escape_string() to rectify this but that is not true.
The only way to stop url injection is to use functions like:
trim(); strip_tags(); htmlentities();
As well as making sure that the number coming though is infact a number.
The mysql_real_escape_string() is to help protect your database from such attacks but using the others safeguard against harsher attacks.
The way i suggest is to use the following:
if(isset($_REQUEST["id"])){ if(!is_int($_REQUEST["id"])){ //redirect this person back to homepage } else { $id_raw = trim(htmlentities($_REQUEST["id"])); $id_secure = mysql_real_escape_string($id_raw); $sql = "SELECT * FROM databasetable WHERE id='".$id_secure."'"; } }
Ok, what was done here is:
For instance a < in html is infact < in html. This is safe in sql.
Now its made it html and stripped spaces we now us the mysql_real_escape_string() which takes out injection strings.
This has now made it safe to input into the database and prevent url injections.
Hope this helped you out and helps prevent your website from being hacked by this manor!
Great, Very nice tutorial, I like don't know about that.
Thanks for giving such an important coding. I always use this when i needed the data from database using id.
Thanks again for nice tutorial.
Hello, My website was recently hacked. Google mentioned url injections were used. I came across your website and the code above and I hope it can help, however I am not a master coder and wanted to just clarify where exactly would I need to add this code to ensure my website is not attacked again. My website is built in wordpress. I hope you can help. Thanks in advance for any help you can provide. David
As your website is a WordPress website, you need to make sure that all plugins are up to date and also the WordPress is using the latest version. If you are still getting hacked I would suggest you disable your plugins
Comments are now closed for this post... – UBL Designs
Nikki 5 Jan, 2012
Thanks, recently been had by this so this will help me in future!