tags:

views:

56

answers:

3

How do I keep session state of a variable throughout a site?

For example:

A user lands on my website, the string generated is

$string = 'uejsh37rhda283jde86541as';

(This string is autogenerated by an xml feed on every page refresh).

Now, everything works so far ok. The problem is when the user clicks on another page on the site, the xml feed creates a new random string.

I know I have to use sessions here, but how exactly?

if(isset($_SESSION[])): 
     ?
else: 
      ?
endif;

Updated code:

if(isset($_SESSION['session'])): 
      $string = $_SESSION['session'];
else: 
      $string = $sessionId;
      $_SESSION['session'] = $string;
endif;

echo $string;
+1  A: 
if (isset($_SESSION['my_string'])) {
    $string = $_SESSION['my_string'];
}
else {
    $string = generate_random_string();
    $_SESSION['my_string'] = $string;
}
// now do something with $string
Lukáš Lalinský
Don't forget the `session_start()`
random
+4  A: 

First of all, you need to call session_start() on all pages that access or manipulate session data.

You can do it like this:

session_start();

if (!isset($_SESSION['string'])) {

  $string = makeString();
  $_SESSION['string'] = $string;

}
code_burgar
Very close, I'm getting somewhere. Can you see my updated code and point out where I'm going wrong please?
Keith Donegan
Keith, can you explain what you are trying to do with the code? It appears as if you are trying to do what php does automatically for you. Have you looked at php's session_id()? Every session started by session_start() gets a unique identifier.
code_burgar
No probs codeburger. This is for a special feed. The feed creates a unique string used for each person accessing the site. It is vital that this string be used. So when the user visits other pages, the company who own the feed can track the user.
Keith Donegan
+1  A: 

Try this:

// call session_start() here if session handler is not started yet
if (isset($_SESSION['random-string'])) {
    $string = $_SESSION['random-string'];
} else {
    $string = generateRandomString();
    $_SESSION['random-string'] = $string;
}
Gumbo