JasonDavis
JasonDavis

Reputation: 48933

Should I be calling a variable that holds a SESSION value instead of calling the actual session in PHP?

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

Upvotes: 4

Views: 150

Answers (2)

lamas
lamas

Reputation: 4598

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

Upvotes: 0

Gumbo
Gumbo

Reputation: 655269

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.

Upvotes: 3

Related Questions