|redirect from autoincrement from 1 every day|
I wanted to attach a unique ID to a link click. At this time it's about 10-35k daily depending on a day. I figured that if I use a date stamp plus an increment of +1, I'll get a unique ID for every click.
How do I setup PHP in the simplest way to do an increment of +1 starting from either 0 or 1 every new day?
This is for a redirect, so all my tracking code is in a PHP script which directs visitors to an ending URL. It's used for affiliate tracking, direct linking from Google, Bing, Yahoo, etc.
Doing the +1 for every hit requires you to
- mutex lock
- read the stored value
- increment the value
- write the new value to storage
unless I'd need 100% sure unique numbers, I'd go for a large random value instead. It's much more efficient and doesn't need any locking nor storage.
128bit random would give you 2^64 tries on average to find a collision (birthday paradox) - for most uses that's more than good enough.
For your use it would be more than enough.
Base64 encoding of the random value makes it safe and relatively compact to transport it.
Actually since it's not cryptographic, you could just use the md5 or sha-1 value of a string composed of the time of day, date, browser string, referrer, some small random value, the IP address, the port number, ... (anything that changes actually)
that would be more than good enough too.
When I need a unique incremental number I concatenate a time/date stamp with the user's remote IP, (and always left-pad each octet with zeros to form a fixed length string).
Take for example March 10, 2013 at 4:15:30pm and a user from "92.256.3.299"
YYYYMMDDhhmmss = 20130310161530 (24hr "military" time with each fragment left-padded with zeros)
IP = 92.256.3.299
w/ left zero padded octets = 092.256.003.299
Remove dots = 092256003299
Concatenate "20130310161530" and "092256003299" and you now have sortable, unique, incremental string of numbers: 20130310161530092256003299
Since the most significant "bits" are to the left, and all are fixed length, they will sort chronologically, (the mathematical value of the IP address is the least significant part of the number and should have little consequence on sorting).
No look-ups, no disk writes, no storage needed!
(NOTE: Yes. I do know IP address octets can only go to "255" -- the "256" and "299" are to anonymize my example)
..and just looking at the number (in logs or elsewhere) tells you Who, What, When.