There are multiple pages. There are links on these pages. These links leads to a page with a form. When the form is submitted, the page that holds the form refreshes itself
This concept is known as Post-Redirect-Get. The question is: is the user always going back to the same static original page, or are there many pages that can lead the user to this form? If the latter is true, simply add the referer ($_SERVER['HTTP_REFERER']
) as a form element to record where they came from. php code:
<?php
class controller {
//for chaining
public static function _() { return new self; }
public function GET() {
//dispay form
}
public function POST() {
//process form
//add errors to session
if (!empty($_SESSION['form errors']) {
$this->redirect($_SERVER['PHP_SELF']);
}
else {
$this->redirect("original-user-location", true, 303);
}
}
private function redirect($loc) {
header("Location: $loc", true, 303);
exit;
}
//ignore PUT, DELETE
public function __call($_, $_) {}
}
controller::_()->$_SERVER['REQUEST_METHOD']();
?>
What I like to do is add to a session variable array each time a page is accessed called "history", and only add to the array if the last $_SESSION['history']
item is not the current url (avoid multiple recent entries for page refresh, form validation failure, etc). Basically a breadcrumb trail of where the user has been. When you process the form - send the user back to whichever array value is most recent, excluding the current form's url if you please. Just make sure to set a default value in case there is no history.
$_SERVER['HTTP_REFERER']
can work sometimes, but Ive had major issues with it, and it doesn't work in a lot of cases (refresh, coming from same page, typing in the form url, coming from an email link, etc.) I strictly avoid it personally as it can lead to erratic behavior and redirect loops if you aren't careful with it. In fact I would just never use it for redirection.