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\HttpFoundation;
15 * RedirectResponse represents an HTTP response doing a redirect.
17 * @author Fabien Potencier <fabien@symfony.com>
19 class RedirectResponse extends Response
24 * Creates a redirect response so that it conforms to the rules defined for a redirect status code.
26 * @param string $url The URL to redirect to. The URL should be a full URL, with schema etc.,
27 * but practically every browser redirects on paths only as well
28 * @param int $status The status code (302 by default)
29 * @param array $headers The headers (Location is always set to the given URL)
31 * @throws \InvalidArgumentException
33 * @see http://tools.ietf.org/html/rfc2616#section-10.3
35 public function __construct($url, $status = 302, $headers = array())
37 parent::__construct('', $status, $headers);
39 $this->setTargetUrl($url);
41 if (!$this->isRedirect()) {
42 throw new \InvalidArgumentException(sprintf('The HTTP status code is not a redirect ("%s" given).', $status));
45 if (301 == $status && !array_key_exists('cache-control', $headers)) {
46 $this->headers->remove('cache-control');
53 public static function create($url = '', $status = 302, $headers = array())
55 return new static($url, $status, $headers);
59 * Returns the target URL.
61 * @return string target URL
63 public function getTargetUrl()
65 return $this->targetUrl;
69 * Sets the redirect target of this response.
71 * @param string $url The URL to redirect to
75 * @throws \InvalidArgumentException
77 public function setTargetUrl($url)
80 throw new \InvalidArgumentException('Cannot redirect to an empty URL.');
83 $this->targetUrl = $url;
86 sprintf('<!DOCTYPE html>
89 <meta charset="UTF-8" />
90 <meta http-equiv="refresh" content="0;url=%1$s" />
92 <title>Redirecting to %1$s</title>
95 Redirecting to <a href="%1$s">%1$s</a>.
97 </html>', htmlspecialchars($url, ENT_QUOTES, 'UTF-8')));
99 $this->headers->set('Location', $url);