views:

54

answers:

2

If a PHP session variable is stored on file (like it is by default) then let's say I store a user's name into a session variable...

$_SESSION['username'] = 'Jason Davis';

Now when a page is built, if I call $_SESSION['username'] 100 times in the process of building a page, would it hit the session files and do a read on them 100 times?

Same thing but with session's being stored in MySQL. Would it query the database 100 times to get the username from the sessions table?

I am just trying to find out if I should be calling the session variable 1 time in a page and then storing it to a local variable and using that for the other 99 times. Like this...

$username = $_SESSION['username'];
echo $username; // 100 times throughout all the files that build my page.

Note: Please realize this is just an example, in reality I will need to access more then just a username session and the 100 times would most likely be less but spread out over multiple session key/values

+3  A: 

No, the session data is read when session_start is called and written when either the script runtime is ended or session_write_close is called.

Gumbo
`$number_of_times_beaten_by_gumbo_today++`
adam
So if I were to change my session to use MySQL for there storage and I call $_SESSION['username'] many time over, it will not keep fetching my session from MySQL either?
jasondavis
@jasondavis: Yes, the session data is only read once when `session_start` is called and then stored in `$_SESSION`.
Gumbo
Thanks, that makes sense!
jasondavis
A: 

The file is only read when you call the session_start() function.

As for MySQL, if you make a query, get the username and store it in a variable, there won't be any additional queries anymore of course. If you store something in a variable it's a copy and doesn't have to do something with the original value you got it from.

best regards, lamas

lamas
Hello I realize that is I store it into a variable that it would not hit the DB again, My question is, will PHP Session's hit it over and over if I do NOT store it into a local variable
jasondavis
In that case it just behaves like Gumbo and I said - You can do whatever you want with $_SESSION and it will just behave like a "normal" variable until you call a session_x() function again :)So no, you don't have to store it in a local variable.But if you don't want to write $_SESSION again and again I suggest doing so!
lamas