Redirecting to the referrer on form submission

后端 未结 2 1684
我在风中等你
我在风中等你 2021-01-19 06:43

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

相关标签:
2条回答
  • 2021-01-19 07:21

    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']();
      ?>
    
    0 讨论(0)
  • 2021-01-19 07:36

    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.

    0 讨论(0)
提交回复
热议问题