mds1256 Posted December 21, 2012 Share Posted December 21, 2012 Hi When you see websites with a url like: test.com/page.php?id=5 What is the best way to make this safe. I was thinking the following: check if $_GET['id'] is set, if not error message check if $_GET['id'] is a integer, if not error message mysqli_real_escape_string on the $_GET['id'] pass the escaped id var into sql where page id = escaped var if no results are found then error message ELSE return page content from database So in theory this should stop someone typing in 99999999999 as the page id in the url. It should also stop any SQL injections and it should also stop someone typing in text rather than a number. And this will also not allow them to return a blank page and should show an appropriate error message e.g. redirect to the custom 404 page? Is this a good way or is there a better way of doing this? Thanks Quote Link to comment Share on other sites More sharing options...
Psycho Posted December 21, 2012 Share Posted December 21, 2012 There is no one size fits all answer because it is entirely dependent upon the purpose. But, I'll provide some best practice advice 1. check if $_GET['id'] is set, if not error message If the value is required for the page you can either use a default value when no ID is passed or provide an appropriate error. 2. check if $_GET['id'] is a integer, if not error message . . . I typically just force the value to be an integer by casting it as an integer or using intval(). For non-integer values it will be set to 0 which - in most cases won't have a corresponding value in the database since auto-int fields typically start at 1. So, the rest of the logic will go as normal and just respond with a "not found" type error (i.e. your #5) 3. mysqli_real_escape_string on the $_GET['id'] This is completely unnecessary if you have already validated if the value is an integer (or forced it to be in int). mysqli_real_escape_string() is only needed for "string' data My logic would probably look something like this $id = (isset($_GET['id'])) ? intval($_GET['id']) : 0; $query = "SELECT * FROM table WHERE id = '{$id}'"; $result = mysql_query($query); if(mysql_num_rows($result)) { //No result found, show appropriate error } else { //Display the record } NOTE: The one thing I left out was any validation needed if the record required specific "rights" for the user to view. In that case you may need to do a check for the user rights before running the query for the record or it may require a more complicated select query Quote Link to comment Share on other sites More sharing options...
mds1256 Posted December 21, 2012 Author Share Posted December 21, 2012 Thanks Psycho! Thanks for helping me on all my other queries too Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.