Cookies or session ?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
amirbwb
Forum Commoner
Posts: 89
Joined: Sat Oct 30, 2010 6:10 pm

Cookies or session ?

Post by amirbwb »

Hello, I created lot of websites for fun, and I used session for storing information, I am in the good way or I should use cookies ?

Code: Select all

if($login){
   $_SESSION['username']=$username;
   $_SESSION['level']=$level;
}
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Cookies or session ?

Post by Apollo »

First of all you never ever store an actual password AT ALL, anywhere.

Anyway, session or cookie: depends on how long you want to store it (and how secure).

Session = stored server side, expires when their "session ends" (usually when their browser closes or after an hour of inactivity or so). People can't access the data (exceptions on shared hosting aside), put they can hijack eachother's session IDs, thus impersonating eachother.

Cookie = stored client side, expires when you want (when their browser closes or at a set date). Of course they can also delete cookies themselves. People could copy eachothers cookies, so hijacking a login and impersonating eachother is a risk here.

To store if a user is logged in, I'd use a cookie (because people usually want to remain logged in when they visit your site next time). But hash the data, and perhaps make it depend on their IP. For example, in the login cookie, store the user ID + a hash of their username+password+IP. If any of those changes, the login cookie will become invalid and they'd have to login again (you have to check this at the top of every page that requires login).
User avatar
egg82
Forum Contributor
Posts: 156
Joined: Sat Oct 01, 2011 9:29 pm
Location: Colorado, USA

Re: Cookies or session ?

Post by egg82 »

how about both? Store the username and an ENCRYPTED password in two cookies.
sanitize the cookies (some people like to mess with cookies) and then grab their info from the database using those cookies.
Set a session and use session variables from then on (session is MUCH more secure)

And remember to set a cookie's expiration date. Without one it acts like a session and is destroyed when the browser is closed
User avatar
amirbwb
Forum Commoner
Posts: 89
Joined: Sat Oct 30, 2010 6:10 pm

Re: Cookies or session ?

Post by amirbwb »

thank you both ... i've been creating website and I only used session is there any problem ?

this is my way:

Code: Select all

$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);

...
$query="SELECT id from login where username = '$username' and password = '$password' ";
$query=mysql_query($query)
$row_query=mysql_fetch_assoc($query);
$num_query=mysql_num_rows($query);

if($num_query_row == '1'){
$_SESSION['username']=$username;
$_SESSION['level']=$row_query['level'];
}else{
$error="Login faild";
}
Is this the correct way to create a login ?
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: Cookies or session ?

Post by flying_circus »

egg82 wrote:how about both? Store the username and an ENCRYPTED password in two cookies. sanitize the cookies (some people like to mess with cookies)
This is exactly why you should not store anything other than navigational data within a cookie, you cannot trust the contents. Usernames are better stored within a session, and a password should never be stored in either a cookie or a session.
egg82 wrote:And remember to set a cookie's expiration date. Without one it acts like a session and is destroyed when the browser is closed
This is because sessions are maintained by the use of a cookie. When you start a session, the session handler sends a cookie with a session id to the client. On each subsequent page request, the client sends the session id back to the web server as a cookie var and that is how your session is perpetuated. Thus, if you clear your cookies, you will lose your session. *Note* this only holds true when session ids are sent through cookies (the most common method). Session ids can also be sent through GET or POST vars.
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: Cookies or session ?

Post by flying_circus »

amirbwb wrote:Is this the correct way to create a login ?
This topic seems to get covered quite often. Let me direct you to a thread that I posted in, scroll down the thread until you find my username and compare the login script that I posted, with the one you are working on.

Good luck!

http://www.devnetwork.net/viewtopic.php?f=1&t=129885
User avatar
egg82
Forum Contributor
Posts: 156
Joined: Sat Oct 01, 2011 9:29 pm
Location: Colorado, USA

Re: Cookies or session ?

Post by egg82 »

flying_circus wrote:
egg82 wrote:how about both? Store the username and an ENCRYPTED password in two cookies. sanitize the cookies (some people like to mess with cookies)
This is exactly why you should not store anything other than navigational data within a cookie, you cannot trust the contents. Usernames are better stored within a session, and a password should never be stored in either a cookie or a session.
egg82 wrote:And remember to set a cookie's expiration date. Without one it acts like a session and is destroyed when the browser is closed
This is because sessions are maintained by the use of a cookie. When you start a session, the session handler sends a cookie with a session id to the client. On each subsequent page request, the client sends the session id back to the web server as a cookie var and that is how your session is perpetuated. Thus, if you clear your cookies, you will lose your session. *Note* this only holds true when session ids are sent through cookies (the most common method). Session ids can also be sent through GET or POST vars.
Look at that, I learned something today!

Anyway, to answer:

Code: Select all

$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);
$username = strip_tags($username);
$password = strip_tags($password);

...
$result = mysql_query("SELECT `id` from `login` where `username`='".$username."' and `password`='".$password."';");

if(mysql_num_rows($result) == 1){
	$row = mysql_fetch_array($result);
	$_SESSION['username']=$row["username"];
	$_SESSION['level']=$row["level"];
}else{
	$error="Login failed";
}
A few small edits, but more or less - yes.
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: Cookies or session ?

Post by flying_circus »

You forgot a cardinal rule about escaping...

Code: Select all

<?php
  # Always test a variables existance before referencing it!!!
  $username = isset($_POST['username']) ? strip_tags($_POST['username']) : '';
  $password = isset($_POST['password']) ? strip_tags($_POST['password']) : '';

  /* ... */
  # Escaping is the final operation performed on a piece of data prior to use in a database query
  $result = mysql_query(sprintf("SELECT `id` FROM `login` WHERE `username`='%s' AND `password`='%s';",
                                mysql_real_escape_string($username),
                                mysql_real_escape_string($password)));

  if(mysql_num_rows($result) == 1) {
    $row = mysql_fetch_array($result);
    # Rather than store a username (part of login credentials) in a session, store the user id instead
    //$_SESSION['username'] = $row["username"];
    $_SESSION['id'] = $row["id"];
    $_SESSION['level'] = $row["level"];
  } else {
    $error = "Login failed";
  }
?>
User avatar
egg82
Forum Contributor
Posts: 156
Joined: Sat Oct 01, 2011 9:29 pm
Location: Colorado, USA

Re: Cookies or session ?

Post by egg82 »

haha whoops, i'm off a bit today. Yeah, I should have tested and stripped before I escaped.

as long as you secure a session (prevent session jacking with session_regenerate_id(false)) it should be fine to store a username in a session. Especially when you use that a lot. Easier to get $_SESSION["user"] than to mysql_query() on every page.
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: Cookies or session ?

Post by flying_circus »

egg82 wrote:as long as you secure a session (prevent session jacking with session_regenerate_id(false)) it should be fine to store a username in a session.
session_regenerate_id() does not secure the session or prevent session jacking, especially when called with the false parameter. You can secure the transmission of the session id by using a secure protocol (https), but simply changing the id will gain you nothing.
egg82 wrote:Especially when you use that a lot. Easier to get $_SESSION["user"] than to mysql_query() on every page.
Every project has its own design goals, in this case it's a matter of convenience (marginal at best) VS a matter of security. It's your call.
User avatar
egg82
Forum Contributor
Posts: 156
Joined: Sat Oct 01, 2011 9:29 pm
Location: Colorado, USA

Re: Cookies or session ?

Post by egg82 »

my understanding of session IDs was if the attacker could get the session ID of, say, an administrator, the attacker then becomes the administrator and takes over the session. Simply regenerating the session ID (depending on how the code was implemented) would be rid of this, and the variables stay the same (in the case of a non-attacker).

That was just my understanding. I don't think, i'm wrong, however. As long as you didn't replace the session variables before you regenerated the ID, you should be golden.
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: Cookies or session ?

Post by flying_circus »

egg82 wrote:my understanding of session IDs was if the attacker could get the session ID of, say, an administrator, the attacker then becomes the administrator and takes over the session.
This part is correct. If the session id is compromised, the compromiser assumes that identity for the duration of the session.
egg82 wrote:Simply regenerating the session ID (depending on how the code was implemented) would be rid of this, and the variables stay the same (in the case of a non-attacker).
What you're actually doing is creating a copy of the current session, to a new session with a different identifier, without deleting the old session.

PHP Doc:
"bool session_regenerate_id ([ bool $delete_old_session = false ] )"

Perhaps the misunderstanding comes from defining what a session actually is. A "session" is nothing more than a text file saved to the hard drive with a serialized array containing the session variables. If you are on a shared web host, you can use php to list the contents of the default php session.save_path, and you'll likely find session files owned by other users applications hosted on the same server. This is why it is very important to change the default session.save_path directive when using the standard php session handler on a shared host.

So, as the client sends the session id in a GPC (GET, POST, or COOKIE) var, the php session handler, upon being invoked, looks for the GPC var named session_name(), which is typically PHPSESSID by default. If the session handler finds a matching file on the hard drive with the supplied session id, it resumes the session. This is why we moved the session id into cookies by default, otherwise we'd all pass around URI's like http://www.example.org?PHPSESSID=abc123. The previous example used to be a real problem as people sent each other links in email or instant messenger.

Now, the last piece of the puzzle. When you close your web browser, it deletes your client side session id cookie. However, the server does not know that you are disconnected for good, so the file still lives on the server. If you manually recreated the cookie with the session id, you can resume your session if you re-open your browser. The cookie lives on the server hard disk until it is picked up by the garbage collector, which is based on random probability.

Either way, it's because of the point about text files above being stored in a default (shared) directory, that we dont put login credentials in sessions. It's because of the last point that we use the TRUE parameter when regenerating sessions id's, and it's because of session id propagation that we regenerate the session id any time there is a change in privilege level. Hopefully your use of SSL is synchronized with privileged activities.
User avatar
egg82
Forum Contributor
Posts: 156
Joined: Sat Oct 01, 2011 9:29 pm
Location: Colorado, USA

Re: Cookies or session ?

Post by egg82 »

nicely put. Wherever I read did NOT say any of that.
I just checked over my site, and by pure coincidence I seem to have done everything correctly (aside from variable storage)

In any case, I stand corrected.
Post Reply