/    Sign up×
Community /Pin to ProfileBookmark

How to access $_session[] ?

Hi!

I have some questions about the wonderful $_session variable and hope to get som helpful answers so that I can continue.

If I have understood it right, $_session variable is like an array. Each time I put something to it, it’s stored after the last time an not cleared between?

So if I have a page where I put something into variable like $_session[‘test’] = ‘1’ and at next call $_session[‘test’] = ‘2’ and so on.

Later on another page I want to get all the information from that session variable, how do I do that? I want to get each part and perhaps put them into ordinary variables or something like that?

?

to post a comment
PHP

8 Comments(s)

Copy linkTweet thisAlerts:
@MindzaiApr 16.2010 — Note that it is $_SESSION not $_session - case matters ?

You can access the data stored in the session superglobal the same as any other array - there is no need to move data out into other variables. For example, if I add something to the $_SESSION superglobal:

[code=php]session_start();
$_SESSION['foo'] = 'bar';[/code]


I can then access this value later on and do whatever I want with it:

[code=php]session_start();
echo $_SESSION['foo'];[/code]


Just think of it as a normal associative array in terms of what you can do with it.
Copy linkTweet thisAlerts:
@pkngauthorApr 16.2010 — OK, thanks!

So I can continue with $_SESSION['foo'] = 'hello'; and $_SESSION['foo'] = '24'; and $_SESSION['foo'] = 'weekend';

But later when I want to access them with echo $_SESSION['foo']; Will foo containe all this bar, hello, 24 and weekend?

Please show me an example how to handle each part? If I want to use echo $_SESSION['foo']; in a loop?

Thanks!
Copy linkTweet thisAlerts:
@criterion9Apr 16.2010 — Check the manual. You are wanting to make an array out of SESSION['foo'].
Copy linkTweet thisAlerts:
@MindzaiApr 16.2010 — As mentioned by criterion, an option is to assign an array to $_SESSION['foo']. The $_SESSION superglobal is just a fancy array, and arrays can contain anything, even other arrays. When you have an array containing another array, it's often referred to as a "multidimensional" array.

In your case however, you may not need a multidimensional array. Don't forget that $_SESSION is itself an array. When you write $_SESSION['foo'] = 'bar', you are telling PHP to assign the string value 'bar' to the $_SESSION array under the key 'foo'. Keys can be either a string or an integer, and values can be anything. If you have multiple values you want to store in $_SESSION, you just have to choose a unique key for each of them. Suppose you want to store a user's username, age and date of birth in the session. You might do this:

[code=php]
$_SESSION['username'] = 'Mindzai'
$_SESSION['age'] = 28;
$_SESSION['dob'] = '1981-09-15';
[/code]


Because $_SESSION is an array, you can then loop over these values like so:

[code=php]foreach($_SESSION as $key => $value) {
echo "$key: $value<br />";
}
/*
output:
username: Mindzai<br />
age: 28<br />
dob: 1981-09-15<br />
*/[/code]


In reality, often you do want to use a multidimensional approach since it allows you to group related data. For example you might do this instead:

[code=php]$_SESSION['userdata'] = array(
'username' => 'Mindzai',
'age' => 28,
'dob' => '1981-09-15'
);[/code]


You could then access the data by looping over the userdata array:


[code=php]foreach($_SESSION['userdata'] as $key => $value) {
echo "$key: $value<br />";
}
/*
output:
username: Mindzai<br />
age: 28<br />
dob: 1981-09-15<br />
*/[/code]
Copy linkTweet thisAlerts:
@pkngauthorApr 16.2010 — Thanks! Lot of useful information! Great! But perhaps I can't do as I was hoping. My thought was to use a $_SESSION like this:

A user can click on a link och image to pick his or her favorite ones. Each link has a ?id= with a number. I want the list to live om during the visitors click between other pages at the site and add new items to the list of favorites, just like a shopping basket. Later the user can view the favorite list of items.

Perhaps a multidimensional array is the best, but I have to increase the key each time when something is added. Then next problem appear, the must perhaps also be a $_session to store the value?

Confusing?! Sorry, but I hope you understand. Thanks ?
Copy linkTweet thisAlerts:
@MindzaiApr 16.2010 — No, what you want is easy to achieve ?

One thing I forgot to mention about arrays in general is that you don't have to specify the key yourself. If you leave out the key, PHP will just use incrementing numbers starting at 0 by default. This is useful for lists of items. For example:

[code=php]
$_SESSION[] = 'foo';
$_SESSION[] = 'bar';
$_SESSION[] = 'baz';
// etc

echo $_SESSION[0]; // foo
echo $_SESSION[2]; // baz
[/code]


So that's the issue with having to specify keys sorted ?

The next part requires the use of another PHP superglobal, $_GET. Again, as with all superglobals, this is just a fancy array, but this ones special trick is to store all of the values from the query string (the bit of the URL after ?).

For example, if a user clicks a link with an href like http://domain.com/script.php?id=123, $_GET will automatically contain the value 123 under the key 'id':

[code=php]
echo $_GET['id']; // 123[/code]


So what you need is a combination of both superglobals and the automatic numbering of array elements:

[code=php]session_start();
$_SESSION['ids'][] = $_GET['id'];[/code]


Each time the above is called, a new item will be added to $_SESSION['ids'] with the value supplied in the URL.

Now, you will want to add some error checking and filtering to the above - for example you will want to make sure id is an integer (inval()) and that $_GET['id'] is set (isset()) for the case where the query string is missing, but that's the basic idea.
Copy linkTweet thisAlerts:
@pkngauthorApr 16.2010 — Thanks a lot! You have given me a lot of knowledge about $_SESSION. But I'm also a little bit confused, since I have always seen the 'key' value just as a name for the $_SESSION and not a 'key' like in an array.

I will try the code tomorrow. Thanks!
Copy linkTweet thisAlerts:
@Jarrod1937Apr 16.2010 — Even though you're just on the basics of $_SESSION, be sure to research php session security before making the site live. Php's raw session's are quite vulnerable to exploits.
×

Success!

Help @pkng spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.6,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...