![]() The example in this article was a scenario of sending a user a verification link to activate an account. There are several applications for one-time use URLs. If the difference is less than or equal to the delta, the link is still “fresh.” Conclusion If the difference is greater than the delta, then the link should be expired. Determining if the link has expired then becomes a simple matter of comparing the current time with the original timestamp and see if the difference between them is less than the expiration delta. If the URL is only supposed to be valid for 24 hours, we have a window of 86,400 seconds. Working within the realm of Unix timestamps, the expiration date would be expressed as an offset in seconds. Throw new Exception("Token has expired.") Going further, we could enforce a 24-hour TTL (time to live) for the URL buy checking the timestamp stored in the table alongside the token. "DELETE FROM pending_users WHERE username = ? AND token = ? AND tstamp = ?", delete token so it can't be used again do one-time action here, like activating a user account Throw new Exception("Valid token not provided.") Prepare("SELECT username, tstamp FROM pending_users WHERE token = ?") We’ll want to record the token along with the username and timestamp in the database so we can reference it later. Once the functions execute, we’ve got a unique 40-character string which we can use as our token to create the one-time URL. The sha1() function calculates the hash of the given string using the US Secure Hash Algorithm 1. The function also accepts an optional Boolean argument to add additional entropy to make the result more unique. Uniqid() accepts a string and returns a unique identifier based on the string and the current time in microseconds. Regardless of how you choose to generate your tokens, you’ll want them to be unpredictable (random) and a low chance of duplication (collision). ![]() There are many ways to generate a token, but here I’ll simply use the uniqid() and sha1() functions. The tstamp field is an unsigned integer field used to store a timestamp indicating when the token was generated and can be used if we want to implement a mechanism by which the token expires after a certain amount of time. I’ll be showing how to generate the token using the sha1() function, which returns a 40-character string, hence the capacity of the token field as 40. The table stores the relevant username, a unique token, and a timestamp. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |