Search code examples
phphttppostbrowserback

PHP: back to previous page loaded with HTTP POST


I have a PHP application with a page that has a form to search data. When i click on Search Button there is a Sumbit to same page with HTTP POST method. At this point i click on one item in result list and go to another page. If i click the browser back button from the new page i receive Document Expired error. Why? What can i try to solve this problem?

Here a schematic recap:

PAGE A -> HTTP Post Submit to PAGE A -> PAGE B -> BACK TO PAGE A -> ERROR

Thanks in advance.


Solution

  • Basically, you don't want a users request to finish when they POST data to an html page. You should redirect them to a GET page, so their browser treats that as their last known location, as redirects are treated as part of the overall request in browsers.

    // receive $_POST
    // ... do work ...
    // success!
    header('Location: /wherever', true, 302);
    

    The Found method is generally used for this, and lets you move from one verb to the next (although, other verbs are also used frequently, such as 303, but... yeah just use 302)

    This should resolve your issue!


    Side Note: This particular use case is where things like Flash sessions are especially useful. You want the data to follow them to the redirected page, so you can say "Oh hey, you logged in!" or whatever. This is their purpose. There's a few ways to skin that beast, but I just wanted to let you know.


    Side Note++: Other users have mentioned it, but it's worth reiterating. While the above solves your problem, the standard convention for search forms is to use GET

    <form method="get" action="/search">
        <input name="q">
        <button type="submit">Search</button>
    </form>
    

    This is done for a few reasons, but specifically so search results are index-able, bookmark-able, and shareable.

    POST is generally reserved for large blobs of data, or sensitive data types. There are more use cases, such as REST Verbs etc, but I'm over simplifying for the point.

    To this point, be sure you urldecode($_GET) your data.