PageRenderTime 25ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/examples/Random/strings.php

http://github.com/ircmaxell/PHP-PasswordLib
PHP | 72 lines | 18 code | 11 blank | 43 comment | 0 complexity | 599c3f426e45e52cf3088cb0ca954b16 MD5 | raw file
  1. <?php
  2. /**
  3. * An example file demonstrating the generation of random strings.
  4. *
  5. * PHP version 5.3
  6. *
  7. * @category PHPPasswordLib-Examples
  8. * @package Random
  9. * @author Anthony Ferrara <ircmaxell@ircmaxell.com>
  10. * @copyright 2011 The Authors
  11. * @license http://opensource.org/licenses/bsd-license.php New BSD License
  12. * @license http://www.gnu.org/licenses/lgpl-2.1.html LGPL v 2.1
  13. */
  14. namespace PasswordLibExamples\Random;
  15. /**
  16. * Let's generate some random strings! For this, we'll use the
  17. * PasswordLib\Random\Factory class to build a random number generator to suit
  18. * our needs here.
  19. */
  20. //We first load the bootstrap file so we have access to the library
  21. require_once dirname(dirname(__DIR__)) . '/lib/PasswordLib/bootstrap.php';
  22. //Now, let's get a random number factory
  23. $factory = new \PasswordLib\Random\Factory;
  24. /**
  25. * Now, since we want a low strength random number, let's get a low strength
  26. * generator from the factory.
  27. *
  28. * If we wanted stronger random numbers, we could change this to medium or high
  29. * but both use significantly more resources to generate, so let's just stick
  30. * with low for the purposes of this example:
  31. */
  32. $generator = $factory->getLowStrengthGenerator();
  33. /**
  34. * We can now start generating our random strings. The generator by default
  35. * outputs full-byte strings (character 0 - 255), so it's not safe to display
  36. * them directly. Instead, let's convert them to hex to show the string.
  37. */
  38. $number = $generator->generate(8);
  39. printf("\nHere's our first random string: %s\n", bin2hex($number));
  40. /**
  41. * We can also base64 encode it to display the string
  42. */
  43. $number = $generator->generate(8);
  44. printf("\nHere's a base64 encoded random string: %s\n", base64_encode($number));
  45. /**
  46. * But, we can also generate random strings against a list of characters. That
  47. * way we can use the random string in user-facing situations: (this can be for
  48. * one-time-use passwords, CRSF tokens, etc).
  49. *
  50. * Now, let's define a string of allowable characters to use for token
  51. * generation.
  52. */
  53. $characters = '0123456789abcdefghijklmnopqrstuvwxyz' .
  54. 'ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%&;<>?';
  55. /**
  56. * After that, we can generate the random string
  57. */
  58. $string = $generator->generateString(16, $characters);
  59. printf("\nHere's our token: %s\n", $string);