March 5, 2012

Getting the previous page GET parameters in PHP

Question by Alex

I have a range of similar pages that have a URL along the lines of www.mydomain.com/group?id=1.

From each of these pages there is a form that posts it’s values to the server. I need to work out what the id of the group was when the form is posted. I’m aware of being able to use $_SERVER['HTTP_REFERER'] and then maybe I could use a regex to get the id. However, I wondered if there was anything in PHP that would allow you to get the previous $_GET variables?

Alternatively, do people think it is a much better idea to store the current group id as a session variable?

Answer by Starx

Yes, Session is the way to go to . Store them and get the groups on every other page, using session . This is a proper way.


Despite, it is also possible to make $_GET available for every page. Using two ways (AFAIK).

  1. Create the exact same URL String with the parameters and send them along, as you are redirecting from page to page.

    • Or use functions like parse_url() to get only the query string and pass them along
  2. Use Session to back up the $_GET and reassign it to $_GET on every page. Put the below snippet or every page you redirect to.

    if(isset($_SESSION['GET_BACKUP']) { //Check if there was a backup before
         $_GET = $_SESSION['GET_BACKUP'];  //if yes use it
    }
    
    if(isset($_GET) && count($_GET)) { //if not and GET value is sent
         $_SESSION['GET_BACKUP'] = $_GET; //backup it
    }
    // Now use the get as you used to via $_GET
    

    Following this way, you will not get an attached data in the URL, which might be undesirable.


Update:

In case you are going with the second option, you should remember that the solution I provided is an demo and will not fit for more than one $_GET group. For multiple pages and storing their SESSIONS, you have to define separate keys to identify the backup. Kinda like

$_SESSION['mypage.php']['GET_BACKUP'] = $_GET;

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!