Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove querystring value on page refresh

Tags:

php

I am redirecting to a different page with Querystring, say

header('location:abc.php?var=1');

I am able to display a message on the redirected page with the help of querystring value by using the following code, say

if (isset ($_GET['var']))
{

    if ($_GET['var']==1) 
    {
        echo 'Done';
    }
}

But my problem is that the message keeps on displaying even on refreshing the page. Thus I want that the message should get removed on page refresh i.e. the value or the querystring should not exist in the url on refresh.

Thanks in advance.

like image 721
Subimal Sinha Avatar asked Apr 29 '13 09:04

Subimal Sinha


3 Answers

You cannot "remove a query parameter on refresh". "Refresh" means the browser requests the same URL again, there's no specific event that is triggered on a refresh that would let you distinguish it from a regular page request.

Therefore, the only option to get rid of the query parameter is to redirect to a different URL after the message has been displayed. Say, using Javascript you redirect to a different page after 10 seconds or so. This significantly changes the user experience though and doesn't really solve the problem.

Option two is to save the message in a server-side session and display it once. E.g., something like:

if (isset($_SESSION['message'])) {
    echo $_SESSION['message'];
    unset($_SESSION['message']);
}

This can cause confusion with parallel requests though, but is mostly negligible.

Option three would be a combination of both: you save the message in the session with some unique token, then pass that token in the URL, then display the message once. E.g.:

if (isset($_GET['message'], $_SESSION['messages'][$_GET['message']])) {
    echo $_SESSION['messages'][$_GET['message']];
    unset($_SESSION['messages'][$_GET['message']]);
}
like image 61
deceze Avatar answered Oct 03 '22 06:10

deceze


Better use a session instead

Assign the value to a session var

$_SESSION['whatever'] = 1;

On the next page, use it and later unset it

if(isset($_SESSION['whatever']) && $_SESSION['whatever'] == 1) {
  //Do whatever you want to do here

  unset($_SESSION['whatever']); //And at the end you can unset the var
}

This will be a safer alternative as it will save you from sanitizing the get value and also the value will be hidden from the users

like image 23
Mr. Alien Avatar answered Oct 03 '22 05:10

Mr. Alien


There's an elegant JavaScript solution. If the browser supports history.replaceState (http://caniuse.com/#feat=history) you can simply call window.history.replaceState(Object, Title, URL) and replace the current entry in the browser history with a clean URL. The querystring will no longer be used on either refresh or back/previous buttons.

like image 31
Christopher Martin Avatar answered Oct 03 '22 04:10

Christopher Martin