24/09 – Dev :: Key-hash Security

  (by )
When programming websites today you always have to worry about the security and many beginners just don’t know how to tackle this. I hope the following will help some of you out there.A very simple yet effective way of making sure that your POST data is secure is to include a security hash. This is far more simple then it sounds, follow the below example and I’m sure you’ll understand.The below goes in form.php/whatever.php

<?PHP $key = '"'.md5("key".date("Ymd").'"'; ?>
<form action="edit.php" method="post">
<input name="hash" type="hidden" value=<?PHP echo $key ?>>

Now this goes in edit.php/whatever.php

if ($_POST['hash'] != md5("key".date("Ymd")) {
  die("Restricted access!");

I think that most of you understands what this does but just in case you don’t, in the form we have our hash key which is unique for your site and changes everyday. In the file that does the actual SQL query/other proccessing script we put in a line of pre that will “die” unless the correct key hash is entered.

Now this is just the basics of what you can do with key hashes, I have elaborated many systems with key hash security to be unique not only for the day but for every edit form, page or cookie. This will of course not stop the most relentless hackers but it will fend of a boatload of the less sofistacted hackers and bots.

Jan-Erik Lysander runs Lysander Consulting who specialise in IT / internet / web development.

Subscribe to our mailing list

* indicates required


  1. On March 18, 2009 at 8:37 am

    Konstantin said:

    Thanks for security key

  2. On October 10, 2008 at 1:24 pm

    Jan-Erik L. said:

    Thank you guys for the comments!

    Cleaning up input before processing it is very important (and should not be forgotten!). You can use the following script to do it very quickly:

    < ?PHP foreach ($_POST as $key => $value) {
    if (empty($_POST[$key])) {$_POST[$key] = NULL;}

    $_POST[$key] = addslashes($value);

    This is again just a very basic script but it will save you a load of code and does the job pretty well. If you’re doing this check within a MySQL connection I would suggest also running mysql_real_escape_string().

  3. On October 7, 2008 at 12:20 pm

    Sven said:

    Although this is a nice solution to ensure that the POST data comes from a valid source (i.e. the originating form) it is still quite easy to manipulate the data in between whilst maintaining a valid hash. It does, as you state, stop most “script kiddies”. but you will still need to do something else very important: Clean and verify the input before processing it.

    I must say though, I like the idea of adding a unique hash to data to verify its integrity. You could make good use of that to prevent cookie modification hacks by “checksumming” the data before populating the cookie.

    Good tip 🙂

  4. On September 28, 2008 at 6:14 pm

    Orlando said:

    many thanks for this, this will come in handy!!!