Jim
Jim

Reputation:

PHP - how to use a session in place of the GET var

I have a dilemma going on here. I need to use a session to navigate records in a foreach loop.

foreach($key as $val)
{
  echo '<tr><td><a href="'.$key.'">$val</a></td></tr>';
}

Ok, the $key in this equasion is my database key and when the user clicks the link, it will take them to the next page. This "next page" parses the data and places it into a query string for the URL. I don't like the way it's working with the query string and want to use a session to handle the $key instead but I dont know how to make that work for a hyperlink. Can someone please give me a hand?

Thanks

The whole thing in a nutshell is that I don't want to get the key off the URL. It has nothing to do with security but I want to put that key into a hidden field so that I can parse it later.

Upvotes: 0

Views: 315

Answers (3)

OIS
OIS

Reputation: 10033

This will hide the key and store it in session. You could also use numeric indexes instead of the md5 and salt if you dont like the long md5 strings, or the uniqid function.

//store this value in a config file
$salt = 'somelongsecretstring';

foreach($key as $val)
{
  $md5 = md5($salt . $key);
  $_SESSION['keys'][$md5] = $key;
  echo '<tr><td><a href="?key='.$md5.'">$val</a></td></tr>';
}

At the next page:

$md5 = $_GET['key'];
if (!isset($_SESSION['keys'][$md5])) {
    //key doesnt exists, redirect to previous page and display error.
}
$key = $_SESSION['keys'][$md5];

Upvotes: 1

EvilChookie
EvilChookie

Reputation: 573

If I understand correctly, all you need to do is add the $key to the current $_SESSION.

foreach ($key as $val){
   $_SESSION['key'] = $key;
   echo '<tr><td><a href="'.$key.'">$val</a></td></tr>';
}

Then, all you have to do is look for $_SESSION['key'] when you want to use it again.

Hope this helps.

Upvotes: -1

Philippe Gerber
Philippe Gerber

Reputation: 17846

That's no good idea. The URI (or URL if you want) identifies a UNIQUE resource. A short example:

Good (unique)
http://example.org/page/1 => GET key = 1
http://example.org/page/2 => GET key = 2

Bad (not unique)
http://example.org/page w/ session key = 1
http://example.org/page w/ session key = 2

Upvotes: 2

Related Questions