Cookies and Sessions
Hi,
I know it's not essesntial to use both cookies and sessions for user managment, but what are the advantages of using both?
It seems that they can both be used to store user information, can they both be used if you want to get data from a database for that user?
for example, if a session is called logged which is used to identify whether the user is logged in - can it be used to get the data from the database
select * from users where user = $logged
or does that have to be a cookie in the sql?
I'm really confused with sessions and cookies, please help if you know!
pr0gr4mm3r posted this at 14:16 — 18th July 2007.
He has: 1,502 posts
Joined: Sep 2006
Cookies and sessions are almost identical when trying to access then in PHP.
For example, to access a saved cookie called 'logged', the variable would be $_COOKIE['logged']. If it was in the session, it would be $_SESSION['logged'].
Personally, I would use the session because then the information is stored on the server and not the user's computer. The only thing that is stored on the user's computer is the session id, or SID.
Assigning information to the session is easy. Just treat $_SESSION like an array and assign variables to it accordingly. The same array will be waiting for you on the next page to be read.
Cookies are set using the setcookie() function.
drew22299 posted this at 15:05 — 18th July 2007.
They have: 105 posts
Joined: Mar 2006
This is abit of a long question but I think I almost understand how to use sessions!
Am I right in guessing that I should set $_SESSION[username] as the one entered in the login textbox and then use the username session variable on all the pages that require the logged in users' information? something like
$query = "SELECT * FROM users WHERE user_name='$user'";
$sql = mysql_query($query);
$sqlinfo = mysql_fetch_array($sql);
$username = $sqlinfo[username];
$_SESSION[username] = $username
I have the following code which is part of the process login script, the logged session variable can't be used for anything other than checking to see if the user is logged in, is that right?
session_start();
session_register(logged);
$_SESSION[logged] = "true";
header("Location: index.php");
pr0gr4mm3r posted this at 15:29 — 18th July 2007.
He has: 1,502 posts
Joined: Sep 2006
You can use it for whatever you want, but that's what it's used for in this case.
A few things though, you should enclose string indexes in single or double quotes. For example, change $_SESSION[logged] to $_SESSION['logged']. Also, $_SESSION[logged] = "true"; should be $_SESSION[logged] = true; because "true" is a string with quotes, and a boolean without them.
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.