Search code examples
phpmysqlsessionsearchback

How to keep track of where a user was in their search results so that we can take them back where they left off?


On one of my PHP sites, we serve up multi-page internal search results that users can browse through. Users can click on any search result and view that individual listing and take an action on that listing.

What I would like to do is keep track of where they were in the search results so that when they take an action on a listing, we can automatically bring them back to where they were, so that they can continue browsing where they left off.

What's the best way to do that? Please note that the search results is not the only way to arrive at a listing, as there are other ways to browse and find a listing, so this solution should obviously only redirect the user back to where they were if and only if they arrived from an actual search.

I'm thinking that storing the URL of the page they are on in a Session variable would be the way to go, but I'm not sure what the best way to do that would be, how to only update the value when it's a search result, how to delete the value after the action is taken, etc.


Solution

  • Briefly:

    Request for listings page or search from user is handled.

    1. Store url $_SESSION['url'] = $requestUrl;
    2. If it's a search request store the search variables: $_SESSION['search_term'] = $searchTerm; $_SESSION['num_results'] = $num; $_SESSION['page'] = $page;
    3. Send response to user.

    Next (individual) listing request from user is handled:

    1. Look up session variables
    2. Craft a 'back to listings' url using these session variables and embed in the response. You could distinguish between a search or a page by the stored url or by checking if search terms have not been set on the session ( in that case unset the search terms in the request above if its not a search).
    3. Send response.