Session questions

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I have a question regarding the usage of sessions and cookies. I'm still a  
fairly new developer, but have built quite a few login-driven applications  
using MySQL for the backend and PHP for the front end.

When I have a login, I generally do the standard algorithm - Check the DB  
for a matching UN/PW, set a session variable as true (or jsut set the  
username as a session var) and then check on if the session['username'] var  
is set. If it's set, they're logged in, if it's not they're not and I  
redirect back to login.

My question has come up recently as I've seen many PHP developers using  
setcookie() and running their code off of this. I'm using the following  
method if there has been a matching un/pw combination found in the DB:

if($totalRows != 0){
    $_SESSION['username'] = $row['usernameFromDB'];

Then, in my include file to check, I'll say something like:

    header("Location: login.php");

What's the difference here between the calling of cookies, or just using the  
$_SESSION variable. Is there a flaw in my login systems here that I may want  
to rethink? Thanks in advance.  

Re: Session questions

As I understand it, having the information in the cookie on the user's
system makes it possible for someone to create a counterfeit cookie and
spoof the system. Using the $_SESSION array keeps it on the server side
and is more secure.


Re: Session questions

Is there any advantage to be gained from using the calls to a cookie then?  
I thought that setting a $_SESSION variable also saved a cookie anyways...

Quoted text here. Click to load it

Re: Session questions

Jon wrote:
Quoted text here. Click to load it


When you use sessions, the data remains on the server.  Only the session id is  
saved as a cookie.  Also, if the user has cookies disabled, the session id can  
be passed as a GET parameter.

Also, the session id is a long string of random characters - very hard to guess,  
and is only valid during that session.  Unlike a user id, which is shorter,  
often times visible (i.e. in discussion boards, etc.) or at least easily  
guessable, chances are the session id will not be guessed.

OTOH, if you store the userid as a cookie on my machine, I can get in and edit  
it - changing the username to 'admin'.  And if you use 'admin' as your logon to  
your private administrative area, I now have access to all of your admin functions.

And you also need to remember that cookies are sent plain text (unless you're  
using https: protocol).  So anyone between you and your site can sniff out your  
userid.  Admittedly chances of this happening to the typical site are small -  
but it is possible.

It always pays to keep sensitive stuff on the server!

Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.

Site Timeline