Is there some way to redirect back to previous route in fat-free framework?
Something similar to redirect->back()
in laravel.
No there's not. If you look at Laravel source code, the back()
function redirects either to the URL contained in the Referer
HTTP header or to the last URL stored in session.
It's up to you to decide which strategy to choose, but both can easily be implemented with F3.
1) Referer header
$f3->reroute($f3->get('SERVER.HTTP_REFERER'))
Pros: easy to implement.
Cons: if the header is not set, it will redirect to the current page. If the header is set to a different domain, it will redirect to another website.
In order to avoid redirecting to another domain, you need to check that the referer domain matches the website domain:
$referer=$f3->get('SERVER.HTTP_REFERER');
if (preg_match('/^https?:\/\/'.preg_quote($f3->HOST,'/').'\//',$referer)) {
// The referer URL belongs to the website domain
$f3->reroute($referer);
} else {
// The referer URL belongs to another domain (or is empty)
// take some action, for example reroute to current page:
$f3->reroute();
// or reroute to homepage
$f3->reroute('/');
}
2) Session URL
// end of index.php
$f3->run();
$f3->set('SESSION.previousUrl',$f3->REALM);
// redirect code:
$f3->reroute($f3->get('SESSION.previousUrl'));
Pros: no risk to redirect to a different domain
Cons: makes it mandatory to use sessions. If you're running a back-office or an app which already makes use of sessions, that's fine, but if you're running a front website, it will prevent pages from being cacheable on the client side.
3) Query string
There's also a third alternative, which could work in some specific cases: passing the original URL in the query string.
<a href="/target?origin=/origin">Click here></a>
// redirect code:
$f3->reroute($f3->get('GET.origin'));