Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This may be the most obvious question but I have seen some controversies on which is the right way
PHP
session_start();
$_SESSION['username'] = $username;


Or

PHP
session_start();
$username = $_SESSION['username'];
Posted
Updated 20-Dec-13 13:35pm
v3

You use the first one to create a session variable "username" to store $username the value of which come from a successful login operation.

Then, the second one uses this session variable to check if a user has logged in or not at the beginning of every secured pages, say

C#
// Check if username session is not set then redirect to login page
if (!isset($_SESSION['username'])) {
header('Location: login.php');
}


A full example here.
 
Share this answer
 
v3
Comments
Braydon 21-Dec-13 23:49pm    
Cool thanks for the tip but it is like you posted of the rim I am asking when I set a variable is it $_SESSION['username'] = $username;

OR

$username = $_SESSION['username'];
?
Peter Leow 22-Dec-13 4:16am    
Ok, to set a session variable, it should be: $_SESSION['username'] = $username;

While to get the value of that session variable, then it should be: $username = $_SESSION['username'];

So the right way depends on the purpose.
Simple Answer is,

If you have a login page and some user logged in. Now you want to store his information like username, fullname, age etc for the session, then you will have to store this data in the $_SESSION variable and the assignment operator '=' is used to assign the value of variable at right hand side to the varaible at left hand side of the operator. So, you have to do,
PHP
$_SESSION['user'] = $username;


But if, you are now on a page that shows on the top, the username of the logged in user, you have to get the data stored in the session variable. This time you have to do,
PHP
$username = $_SESSION['user'];


Obviously, both the statements are correct to their purpose. I hope it helped. :)

With Regards
Tushar Srivastava
 
Share this answer
 
Comments
Braydon 25-Dec-13 20:15pm    
Awesome! Thanks!
Er. Tushar Srivastava 26-Dec-13 4:48am    
I am happy to help :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900