Skip to content

Instantly share code, notes, and snippets.

@HendrikEduard
Last active August 15, 2018 15:40
Show Gist options
  • Save HendrikEduard/86d456dc38d5d65d28e26169e425ad42 to your computer and use it in GitHub Desktop.
Save HendrikEduard/86d456dc38d5d65d28e26169e425ad42 to your computer and use it in GitHub Desktop.
PHP function to generate a secure token to use in a hidden field in forms.
<?php
function form_token() {
$token = bin2hex(random_bytes(33));
return $token;
} // Usage
// $form_token = form_token();
// echo "$form_token";
Copyright 2018 Hendrik Eduard Kuiper
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@HendrikEduard
Copy link
Author

Apologies, there was a typo, it has been fixed.

This has been tested on https://3v4l.org/ and these are the results:

Output for 7.2.8: 74ecfae571d7a4ba9936acc6c093c17baa8f24aa881a85cbe0f92e10d0f9d2a857
Output for 7.2.7: ef4a95f343b3ba0da50afac0d6f6cecaf4e8885d8115b54a7327126ce528fe4582
Output for 7.2.6: 9774eda8c4ddc19842dc4c580ba1ee3b995c40a804a5b64e37c9de48de2f074f1a

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment