UriSigner.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel;
  11. /**
  12. * Signs URIs.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class UriSigner
  17. {
  18. private $secret;
  19. /**
  20. * Constructor.
  21. *
  22. * @param string $secret A secret
  23. */
  24. public function __construct($secret)
  25. {
  26. $this->secret = $secret;
  27. }
  28. /**
  29. * Signs a URI.
  30. *
  31. * The given URI is signed by adding a _hash query string parameter
  32. * which value depends on the URI and the secret.
  33. *
  34. * @param string $uri A URI to sign
  35. *
  36. * @return string The signed URI
  37. */
  38. public function sign($uri)
  39. {
  40. return $uri.(false === (strpos($uri, '?')) ? '?' : '&').'_hash='.$this->computeHash($uri);
  41. }
  42. /**
  43. * Checks that a URI contains the correct hash.
  44. *
  45. * The _hash query string parameter must be the last one
  46. * (as it is generated that way by the sign() method, it should
  47. * never be a problem).
  48. *
  49. * @param string $uri A signed URI
  50. *
  51. * @return Boolean True if the URI is signed correctly, false otherwise
  52. */
  53. public function check($uri)
  54. {
  55. if (!preg_match('/^(.*)(?:\?|&)_hash=(.+?)$/', $uri, $matches)) {
  56. return false;
  57. }
  58. return $this->computeHash($matches[1]) === $matches[2];
  59. }
  60. private function computeHash($uri)
  61. {
  62. return urlencode(base64_encode(hash_hmac('sha1', $uri, $this->secret, true)));
  63. }
  64. }