4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpKernel;
17 * @author Fabien Potencier <fabien@symfony.com>
25 * @param string $secret A secret
26 * @param string $parameter Query string parameter to use
28 public function __construct($secret, $parameter = '_hash')
30 $this->secret = $secret;
31 $this->parameter = $parameter;
37 * The given URI is signed by adding the query string parameter
38 * which value depends on the URI and the secret.
40 * @param string $uri A URI to sign
42 * @return string The signed URI
44 public function sign($uri)
46 $url = parse_url($uri);
47 if (isset($url['query'])) {
48 parse_str($url['query'], $params);
53 $uri = $this->buildUrl($url, $params);
55 return $uri.(false === strpos($uri, '?') ? '?' : '&').$this->parameter.'='.$this->computeHash($uri);
59 * Checks that a URI contains the correct hash.
61 * @param string $uri A signed URI
63 * @return bool True if the URI is signed correctly, false otherwise
65 public function check($uri)
67 $url = parse_url($uri);
68 if (isset($url['query'])) {
69 parse_str($url['query'], $params);
74 if (empty($params[$this->parameter])) {
78 $hash = urlencode($params[$this->parameter]);
79 unset($params[$this->parameter]);
81 return $this->computeHash($this->buildUrl($url, $params)) === $hash;
84 private function computeHash($uri)
86 return urlencode(base64_encode(hash_hmac('sha256', $uri, $this->secret, true)));
89 private function buildUrl(array $url, array $params = array())
91 ksort($params, SORT_STRING);
92 $url['query'] = http_build_query($params, '', '&');
94 $scheme = isset($url['scheme']) ? $url['scheme'].'://' : '';
95 $host = isset($url['host']) ? $url['host'] : '';
96 $port = isset($url['port']) ? ':'.$url['port'] : '';
97 $user = isset($url['user']) ? $url['user'] : '';
98 $pass = isset($url['pass']) ? ':'.$url['pass'] : '';
99 $pass = ($user || $pass) ? "$pass@" : '';
100 $path = isset($url['path']) ? $url['path'] : '';
101 $query = isset($url['query']) && $url['query'] ? '?'.$url['query'] : '';
102 $fragment = isset($url['fragment']) ? '#'.$url['fragment'] : '';
104 return $scheme.$user.$pass.$host.$port.$path.$query.$fragment;