Advertisements

How to generate a unique time-based hash in PHP

This PHP code is especially handy if you want to generate a time-based hash for some security purpose. You can adjust the code to generate hashes every month, every day, or down to every second if that’s what you want. These can be used to generate automatically-changing passwords, password salts, time-based challenges, etc.

NOTE: This is example code only and shouldn’t be copy/pasted for use in a production environment. Instead, modify the code below and change the hash function, the date string, and maybe add your own customizations. See the PHP date() and hash() manual pages for reference.

<?php
// length of hash to generate, up to the output length of the hash function used
$length = 12;
// The following should retrieve the date down to your desired resolution.
// If you want a daily code, retrieve only the date-specific parts
// For hourly resolution, retrieve the date and hour, but no minute parts
$today = date("m.d.y"); // e.g. "03.10.01"
$out = substr(hash('md5', $today), 0, $length); // Hash it
echo "$out";
?>

I’m sure there are plenty of other ways, but this is a code snippet that I used. Feel free to share your thoughts on this in the comments below, thanks!

Advertisements