Application::redirect
Redirect to another URL and stop
Description
public void Application::redirect( string $url )
Send a Location header (HTTP 302) and end the response. Code after redirect() is not run.
redirect() does not call exit: it throws Fegg\Http\Halt, which the dispatcher catches before it writes the session and sends the response. There is no need to write exit after it. A catch (\Throwable $e) around redirect() must rethrow Fegg\Http\Halt (see Ending a response); catch (\Exception $e) is not affected.
- A URL starting with
http://orhttps://is used as is. - Any other URL is a path inside the site. A
/is added at the start if missing, a trailing/is added when the path has no extension (to avoid a second redirect, see URL), and the current protocol, domain and base path are added in front. This also works when the site is installed in a subdirectory.
Arguments
| Name | Data type | Default | Remarks |
|---|---|---|---|
| $url | string | Absolute URL, or a path inside the site |
Example
Controller
// -> https://example.com/news/
$this->redirect('/news/');
// -> https://example.com/news/ (slashes added)
$this->redirect('news');
// -> https://example.com/contact/result.html
$this->redirect('/contact/result.html');
// -> https://www.example.org/
$this->redirect('https://www.example.org/');
Do not pass a URL taken from the request (for example $this->in('return_to')) without checking it, or the site becomes an open redirect.
Inside try / catch
Controller
try {
$this->_save($data);
$this->redirect('/entry/done/');
} catch (\Fegg\Http\Halt $halt) {
throw $halt;
} catch (\Throwable $e) {
\Fegg\Log::error('Entry could not be saved', array('exception' => $e));
$this->redirect('/entry/error/');
}