Jump to content


Photo

Cookie Vs Sessions


  • Please log in to reply
25 replies to this topic

#21 gerrydewar

gerrydewar
  • Members
  • PipPipPip
  • Advanced Member
  • 36 posts

Posted 28 March 2006 - 09:14 PM

[!--quoteo(post=354800:date=Mar 14 2006, 09:14 AM:name=txmedic03)--][div class=\'quotetop\']QUOTE(txmedic03 @ Mar 14 2006, 09:14 AM) View Post[/div][div class=\'quotemain\'][!--quotec--]
Now that you have your sessions table and your sessions up and running, you need a way for users to log in. You can use a form that gets submitted to a page to process the login or you could use the http authentication method. There is an example of this in the tutorials of this site and I would be happy to review the modifications to make this work with the snippets I am posting. Now this will be a page I will call login.php to process the login.

Additionally, I have written this to restrict accounts to only one login per username. If this is not something you are interested in I can point out the specific lines to change.

<?php

$link = mysql_connect('database host address', 'username', 'password') or die("MySQL: ".mysql_error());
mysql_select_db('database name', $link) or die("MySQL: ".mysql_error());

if ( isset($_GET['logout']) ) {
  // We are logging out, but we want to maintain the session as a guest user.
  mysql_query("UPDATE sessions SET uid=-1 WHERE sid='".session_id()."' LIMIT 1", $link);
  mysql_query("UPDATE sessions SET timeout=".(time()+600)." WHERE sid='".session_id()."' LIMIT 1", $link);
  mysql_query("UPDATE sessions SET level='0' WHERE sid='".session_id()."' LIMIT 1", $link);  
  header("Location: index.php"); // We are done head back to the main page. (This could also go to the refering page.)
} else {
  // We are attempting to login now.
  $row = mysql_fetch_assoc(mysql_query("SELECT * FROM users WHERE name='".$_POST['username']."' LIMIT 1", $link));
  if ( mysql_num_rows(mysql_query("SELECT * FROM sessions WHERE uid=".$row['id']." LIMIT 1", $link)) != 1 ) {
    if ( $_POST['password'] == $row['pass'] ) {
      // Username/Password pair verified change the session from guest to admin or user as the case may be.
      mysql_query("UPDATE sessions SET uid=".$row['id']." WHERE sid='".session_id()."' LIMIT 1", $link);
      mysql_query("UPDATE sessions SET timeout=".(time()+600)." WHERE sid='".session_id()."' LIMIT 1", $link);
      header("Location: index.php"); // We are logged in head over to the main page.
    } else {
      echo "      <span class=\"error\">Invalid username/password.</span>\r\n";
    }
  } else {
    echo "      <span class=\"error\">User already logged in.</span>\r\n";
    echo "      <p>We do not allow multiple sessions for the same user. If this is your account this might mean that someone has gained access to your username and password without your consent. If this is the case, please contact an administrator about changing your password.</p>\r\n";
  }
}
mysql_close($link);

?>

Now this won't function without having a table full of users. That's our next step, to create our users table and put some users in it so they can access the site. For right now, I must go and get some sleep. This will give you a chance to review everything and ask questions on anything you do not understand. I might write an actual tutorial later which will break the code down and explain it step by step.
[/quote]

This may sound like a stupid question but i'm going to ask it anyway. I have created this login page and added a form at the bottom where users can enter username and password. However, do i also require the session start script that creates the session table at the top of this login.php page? The reason i ask is surely this part of the code will always return nothing because the session table hasn't been created yet.

if ( mysql_num_rows(mysql_query("SELECT * FROM sessions WHERE uid=".$row['id']." LIMIT 1", $link)) != 1 ) {

The login.php page is always going to be the first page called. How can you select all from session when session doesn't exist? Also session won't exist until someone logs in. When i try to run my login.php script with the code contained above i get a warning:mysql_num_rows():supplied argument is not a valid MySQL result resource on the line shown above. Can someone perhaps explain what code needs to be in my login page?

#22 txmedic03

txmedic03
  • Members
  • PipPipPip
  • Advanced Member
  • 313 posts
  • LocationCall, TX, USA

Posted 29 March 2006 - 01:47 AM

The sessions table has three user levels admin, user and guest (on my particular setup anyway). When someone visits the page it creates a "guest" session for the live counter to use. Since I wrote this to be integrated with a live counter, you would need to make some modifications so you do not need the session_start on the login page.

It seems that you found something I overlooked when I wrote this code. When the user does not previously exist it returns an invalid query result. I have made the needed changes in my earlier post to fix the code. I look forward to any more questions or comments you may have.

if (mysql_num_rows(mysql_query("SELECT username FROM users WHERE username='".$_POST['username']."' LIMIT 1", $conn)) == 1) $error .= "Username already taken.<br />\r\n";

SEMPER FIDELIS!

I can't stop you from doing something silly, but at least I can help you do it right.


#23 gerrydewar

gerrydewar
  • Members
  • PipPipPip
  • Advanced Member
  • 36 posts

Posted 29 March 2006 - 09:16 PM

I've tried to run these scripts without success. Now i've no doubt the error is on my part and not yours. My login.php page constantly gave me the invalid query result and header problems. So i got a bit adventurous and decided to mix and match your login script with the script you suggested we put at the top of every page. My login.php now looks like the following:

<?php
if(isset($_POST['submit'])){
session_start();
$link = mysql_connect('localhost', 'root', '********') or die("MySQL: ".mysql_error());
mysql_select_db('project', $link) or die("MySQL: ".mysql_error());

// Since this may be the first time running the script we need to make sure we have a sessions table.
// We will do it with a simple MySQL Query.  You can disect the following query to see how it works.

mysql_query("CREATE TABLE IF NOT EXISTS `sessions` (`id` int(11) NOT NULL auto_increment,`uid` int(11) NOT NULL, `timeout` int(11) NOT NULL default '0', PRIMARY KEY  (`id`))", $link);

// We are attempting to login now.
  $row = mysql_fetch_assoc(mysql_query("SELECT * FROM users WHERE email='".$_POST['Login_email']."' LIMIT 1", $link));
  if(mysql_num_rows(mysql_query("SELECT * FROM sessions WHERE uid=".$row['user_id']." LIMIT 1", $link)) != 1 ) {
    if ( $_POST['Password'] == $row['password'] ) {
      // Username/Password pair verified change the session from guest to admin or user as the case may be.

      // If you did not already have a session assigned to you create one now.

      if (!is_array($session) ) {
        mysql_query("INSERT INTO sessions (uid, timeout) values ('".$row['user_id']."', ".(time()+600).")", $link);
        $session = mysql_fetch_assoc(mysql_query("SELECT * FROM sessions WHERE sid='".session_id()."' LIMIT 1", $link));
      }

      mysql_query("UPDATE sessions SET uid=".$row['user_id']." WHERE sid='".session_id()."' LIMIT 1", $link);
      mysql_query("UPDATE sessions SET timeout=".(time()+600)." WHERE sid='".session_id()."' LIMIT 1", $link);
      header("Location: logged_in2.php"); // We are logged in head over to the main page.
    } else {
      echo "<span class=\"error\">Invalid username/password.</span>\r\n";
    }
  } else {
    echo "<span class=\"error\">User already logged in.</span>\r\n";
    echo "<p>We do not allow multiple sessions for the same user. If this is your account this might mean that someone has gained access to your username and password without your consent. If this is the case, please contact an administrator about changing your password.</p>\r\n";
  }

mysql_close($link);
}else{

?>
<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

    <head>
    <meta http-equiv="content-type"content="text/html;charset=encoding"/>
    <title>Login</title>
    <h2>Login page</h2>
    </head>

    <body>
        <form method="POST" action="<?php echo "$PHP_SELF";?>"<font face="Arial">
        <fieldset>
            <b><font size="2">Email: </font></b><input type="text" name="Login_email" size="40" maxlength="255"><br\>
            <b><font size="2"><br>Password: </font></b><input type="password" name="Password" size="16" maxlength="255"><br\>
            <input type="submit" name="submit" value="Login!"><font size="2"> </font>
        </fieldset>
        </form>
        <p>If you have yet to register for an account please follow the link below to create one.</p><p><font face="Arial" size="2"><a href="register.php">Register for an account</a></font></p>
    </body>

    <?
    }
    ?>
</html>

Now i'm not really bothered about session id's or tracking ip's so i took that out. I needed to put the session_start at the top on my login page in order to get rid of my errors. I'll perhaps try to move it to after i have successfully matched passwords etc so a session does not start if i have any validation problems.

One problem i am having is getting any info into my session table. I can create the session table when my login.php runs initially but when i log in then check the contents of my table all i get is an empty set. I cannot see where the problem lies. Any idea?

#24 txmedic03

txmedic03
  • Members
  • PipPipPip
  • Advanced Member
  • 313 posts
  • LocationCall, TX, USA

Posted 29 March 2006 - 10:56 PM

I'll have to look over your code to be able to make suggestions on changes, but don't fear session_start(). session_start() does not mean that the user is logged in. It only means that you have a session where you can store information that will carry throughout the domain. With my particular script the session is not used for anything except creating a unique identifier for the individual that comes to the site.

I think I'll probably work on a "lite" version later.

SEMPER FIDELIS!

I can't stop you from doing something silly, but at least I can help you do it right.


#25 gzabriskie

gzabriskie
  • New Members
  • Pip
  • Newbie
  • 1 posts

Posted 31 March 2006 - 12:42 PM

To txmedic03,

I have been scratching my head for about a week trying to come up with a solution to limiting the number of logins a user can have, and this little forum topic did the trick. Your examples worked great. I already had an authentication for logging in I just added the sessions table and the checks by adding the first part of your code at the top of each page.

I use PEAR so I had to make adjustments to the code for my queries but all in all it was pretty simple. It works great!

Thanks for your contributions, you saved me a lot of time!

#26 txmedic03

txmedic03
  • Members
  • PipPipPip
  • Advanced Member
  • 313 posts
  • LocationCall, TX, USA

Posted 01 April 2006 - 09:42 PM

[!--quoteo(post=360338:date=Mar 31 2006, 06:42 AM:name=gzabriskie)--][div class=\'quotetop\']QUOTE(gzabriskie @ Mar 31 2006, 06:42 AM) View Post[/div][div class=\'quotemain\'][!--quotec--]
To txmedic03,

I have been scratching my head for about a week trying to come up with a solution to limiting the number of logins a user can have, and this little forum topic did the trick. Your examples worked great. I already had an authentication for logging in I just added the sessions table and the checks by adding the first part of your code at the top of each page.

I use PEAR so I had to make adjustments to the code for my queries but all in all it was pretty simple. It works great!

Thanks for your contributions, you saved me a lot of time!
[/quote]

I'm glad I could help. As soon as I get a change I'm going to write the "lite" version as well as possibly some improvements I think I might be able to make to the existing code.

SEMPER FIDELIS!

I can't stop you from doing something silly, but at least I can help you do it right.





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users