Jump to content

From Cookies to Session...


eaglelegend

Recommended Posts

I have a site, obviously, but it is using cookies, however I need too change it to sessions asap, before I get millions of users you know, then it will be hard to shift them to the new login without affecting them that much, anyway how do I change this, because there are VERY important imformation inside these cookies, and I would like to change it all to sessions.

 

Cookie - original site config

<?php
ob_start();

$host = "HOST";
$user = "USER"; //EDIT
$pass = "PASS"; //EDIT
$db = "DB"; //EDIT

mysql_pconnect($host, $user, $pass);
mysql_select_db($db);


$SITEURL = "http://www.eaglelegend.com/"; //EDIT

$items_path = "ROOT/eaglelegend.com/FILE"; //EDIT

$Z = "";

if($_COOKIE['ELv2']) {
$ms = mysql_query("SELECT * FROM `members` WHERE `username`='{$_COOKIE['ELv2']}'");
while($mr = mysql_fetch_array($ms)) {
 	$POINTS = $mr["points"];
 	$MONEY = $mr["money"];
}
}

$style_file = "style.css";

$site_title = "Eagle Legend"; //EDIT

$footer = "© Copyright MCMXCVII - MMVIII Eagle Legend. Please Read our Privacy & Cookie Policy before using this site! at www.eaglelegend.com/privacy.php</font>"; //EDIT
?> 

 

Session - new code, that dont include my site...

 

<?php
include("constants.php");
      
class MySQLDB
{
   var $connection;         //The MySQL database connection
   var $num_active_users;   //Number of active users viewing site
   var $num_active_guests;  //Number of active guests viewing site
   var $num_members;        //Number of signed-up users
   /* Note: call getNumMembers() to access $num_members! */

   /* Class constructor */
   function MySQLDB(){
      /* Make connection to database */
      $this->connection = mysql_connect("SERVER", "USERNAME", "PASS") or die(mysql_error());
      mysql_select_db("DB", $this->connection) or die(mysql_error());
      
      /**
       * Only query database to find out number of members
       * when getNumMembers() is called for the first time,
       * until then, default value set.
       */
      $this->num_members = -1;
      
      if(TRACK_VISITORS){
         /* Calculate number of users at site */
         $this->calcNumActiveUsers();
      
         /* Calculate number of guests at site */
         $this->calcNumActiveGuests();
      }
   }

   /**
    * confirmUserPass - Checks whether or not the given
    * username is in the database, if so it checks if the
    * given password is the same password in the database
    * for that user. If the user doesn't exist or if the
    * passwords don't match up, it returns an error code
    * (1 or 2). On success it returns 0.
    */
   function confirmUserPass($username, $password){
      /* Add slashes if necessary (for query) */
      if(!get_magic_quotes_gpc()) {
      $username = addslashes($username);
      }

      /* Verify that user is in database */
      $q = "SELECT password FROM ".TBL_USERS." WHERE username = '$username'";
      $result = mysql_query($q, $this->connection);
      if(!$result || (mysql_numrows($result) < 1)){
         return 1; //Indicates username failure
      }

      /* Retrieve password from result, strip slashes */
      $dbarray = mysql_fetch_array($result);
      $dbarray['password'] = stripslashes($dbarray['password']);
      $password = stripslashes($password);

      /* Validate that password is correct */
      if($password == $dbarray['password']){
         return 0; //Success! Username and password confirmed
      }
      else{
         return 2; //Indicates password failure
      }
   }
   
   /**
    * confirmUserID - Checks whether or not the given
    * username is in the database, if so it checks if the
    * given userid is the same userid in the database
    * for that user. If the user doesn't exist or if the
    * userids don't match up, it returns an error code
    * (1 or 2). On success it returns 0.
    */
   function confirmUserID($username, $userid){
      /* Add slashes if necessary (for query) */
      if(!get_magic_quotes_gpc()) {
      $username = addslashes($username);
      }

      /* Verify that user is in database */
      $q = "SELECT userid FROM ".TBL_USERS." WHERE username = '$username'";
      $result = mysql_query($q, $this->connection);
      if(!$result || (mysql_numrows($result) < 1)){
         return 1; //Indicates username failure
      }

      /* Retrieve userid from result, strip slashes */
      $dbarray = mysql_fetch_array($result);
      $dbarray['userid'] = stripslashes($dbarray['userid']);
      $userid = stripslashes($userid);

      /* Validate that userid is correct */
      if($userid == $dbarray['userid']){
         return 0; //Success! Username and userid confirmed
      }
      else{
         return 2; //Indicates userid invalid
      }
   }
   
   /**
    * usernameTaken - Returns true if the username has
    * been taken by another user, false otherwise.
    */
   function usernameTaken($username){
      if(!get_magic_quotes_gpc()){
         $username = addslashes($username);
      }
      $q = "SELECT username FROM ".TBL_USERS." WHERE username = '$username'";
      $result = mysql_query($q, $this->connection);
      return (mysql_numrows($result) > 0);
   }
   
   /**
    * usernameBanned - Returns true if the username has
    * been banned by the administrator.
    */
   function usernameBanned($username){
      if(!get_magic_quotes_gpc()){
         $username = addslashes($username);
      }
      $q = "SELECT username FROM ".TBL_BANNED_USERS." WHERE username = '$username'";
      $result = mysql_query($q, $this->connection);
      return (mysql_numrows($result) > 0);
   }
   
   /**
    * addNewUser - Inserts the given (username, password, email)
    * info into the database. Appropriate user level is set.
    * Returns true on success, false otherwise.
    */
   function addNewUser($username, $password, $email){
      $time = time();
      /* If admin sign up, give admin user level */
      if(strcasecmp($username, ADMIN_NAME) == 0){
         $ulevel = ADMIN_LEVEL;
      }else{
         $ulevel = USER_LEVEL;
      }
      $q = "INSERT INTO ".TBL_USERS." VALUES ('$username', '$password', '0', $ulevel, '$email', $time)";
      return mysql_query($q, $this->connection);
   }
   
   /**
    * updateUserField - Updates a field, specified by the field
    * parameter, in the user's row of the database.
    */
   function updateUserField($username, $field, $value){
      $q = "UPDATE ".TBL_USERS." SET ".$field." = '$value' WHERE username = '$username'";
      return mysql_query($q, $this->connection);
   }
   
   /**
    * getUserInfo - Returns the result array from a mysql
    * query asking for all information stored regarding
    * the given username. If query fails, NULL is returned.
    */
   function getUserInfo($username){
      $q = "SELECT * FROM ".TBL_USERS." WHERE username = '$username'";
      $result = mysql_query($q, $this->connection);
      /* Error occurred, return given name by default */
      if(!$result || (mysql_numrows($result) < 1)){
         return NULL;
      }
      /* Return result array */
      $dbarray = mysql_fetch_array($result);
      return $dbarray;
   }
   
   /**
    * getNumMembers - Returns the number of signed-up users
    * of the website, banned members not included. The first
    * time the function is called on page load, the database
    * is queried, on subsequent calls, the stored result
    * is returned. This is to improve efficiency, effectively
    * not querying the database when no call is made.
    */
   function getNumMembers(){
      if($this->num_members < 0){
         $q = "SELECT * FROM ".TBL_USERS;
         $result = mysql_query($q, $this->connection);
         $this->num_members = mysql_numrows($result);
      }
      return $this->num_members;
   }
   
   /**
    * calcNumActiveUsers - Finds out how many active users
    * are viewing site and sets class variable accordingly.
    */
   function calcNumActiveUsers(){
      /* Calculate number of users at site */
      $q = "SELECT * FROM ".TBL_ACTIVE_USERS;
      $result = mysql_query($q, $this->connection);
      $this->num_active_users = mysql_numrows($result);
   }
   
   /**
    * calcNumActiveGuests - Finds out how many active guests
    * are viewing site and sets class variable accordingly.
    */
   function calcNumActiveGuests(){
      /* Calculate number of guests at site */
      $q = "SELECT * FROM ".TBL_ACTIVE_GUESTS;
      $result = mysql_query($q, $this->connection);
      $this->num_active_guests = mysql_numrows($result);
   }
   
   /**
    * addActiveUser - Updates username's last active timestamp
    * in the database, and also adds him to the table of
    * active users, or updates timestamp if already there.
    */
   function addActiveUser($username, $time){
      $q = "UPDATE ".TBL_USERS." SET timestamp = '$time' WHERE username = '$username'";
      mysql_query($q, $this->connection);
      
      if(!TRACK_VISITORS) return;
      $q = "REPLACE INTO ".TBL_ACTIVE_USERS." VALUES ('$username', '$time')";
      mysql_query($q, $this->connection);
      $this->calcNumActiveUsers();
   }
   
   /* addActiveGuest - Adds guest to active guests table */
   function addActiveGuest($ip, $time){
      if(!TRACK_VISITORS) return;
      $q = "REPLACE INTO ".TBL_ACTIVE_GUESTS." VALUES ('$ip', '$time')";
      mysql_query($q, $this->connection);
      $this->calcNumActiveGuests();
   }
   
   /* These functions are self explanatory, no need for comments */
   
   /* removeActiveUser */
   function removeActiveUser($username){
      if(!TRACK_VISITORS) return;
      $q = "DELETE FROM ".TBL_ACTIVE_USERS." WHERE username = '$username'";
      mysql_query($q, $this->connection);
      $this->calcNumActiveUsers();
   }
   
   /* removeActiveGuest */
   function removeActiveGuest($ip){
      if(!TRACK_VISITORS) return;
      $q = "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE ip = '$ip'";
      mysql_query($q, $this->connection);
      $this->calcNumActiveGuests();
   }
   
   /* removeInactiveUsers */
   function removeInactiveUsers(){
      if(!TRACK_VISITORS) return;
      $timeout = time()-USER_TIMEOUT*60;
      $q = "DELETE FROM ".TBL_ACTIVE_USERS." WHERE timestamp < $timeout";
      mysql_query($q, $this->connection);
      $this->calcNumActiveUsers();
   }

   /* removeInactiveGuests */
   function removeInactiveGuests(){
      if(!TRACK_VISITORS) return;
      $timeout = time()-GUEST_TIMEOUT*60;
      $q = "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE timestamp < $timeout";
      mysql_query($q, $this->connection);
      $this->calcNumActiveGuests();
   }
   
   /**
    * query - Performs the given query on the database and
    * returns the result, which may be false, true or a
    * resource identifier.
    */
   function query($query){
      return mysql_query($query, $this->connection);
   }
};

/* Create database connection */
$database = new MySQLDB;

$SITEURL = "http://game.eaglelegend.com/"; //EDIT

$items_path = "/misc/39/000/171/334/2/user/web/game.eaglelegend.com/images"; //EDIT

$Z = "";

if($_COOKIE['ELv2']) {
$ms = mysql_query("SELECT * FROM `members` WHERE `username`='{$_COOKIE['ELv2']}'");
while($mr = mysql_fetch_array($ms)) {
 	$POINTS = $mr["points"];
 	$MONEY = $mr["money"];
}
}

$style_file = "style.css";

$site_title = "Eagle Legend"; //EDIT

$footer = "© Copyright MCMXCVII - MMVIII Eagle Legend. Please Read our Privacy & Cookie Policy before using this site! at www.eaglelegend.com/privacy.php</font>"; //EDIT
?>

Link to comment
https://forums.phpfreaks.com/topic/100272-from-cookies-to-session/
Share on other sites

Sessions uses cookies unless otherwise specified.

 

What data are you storing in the cookie? (username?), and what purpose is this cookie for? (To keep the user logged in?)

-----

 

If my assumptions are correct, you will still need cookies to keep the user logged if he/she closes the browser. Sessions have a lifetime (one reason because they use cookies, the cookie is not set with a time to live and so it deletes itself when the browser closes, ie session ends).

 

Session cookies store the KEY of the session (or PHPSESSID). The actual information is stored in a session file on the server (usually above the top-level domain folder).

 

Sessions are for active use (i would assume - its how ive always seen people use them), cookies are more flexible in the way of expiration.

-------

 

If you want to keep users logged in for a certain period of time, then you need to keep at least one cookie.

If you want the login to end when the client closes the browser/visits a session-free page, then use solely sessions.

 

Its a good idea to mix them up. Sessions for active data (loggedin = true), and cookies for extended login periods (user=name&pass=md5)

 

hope this helps,

lol i seem to have baffled you :P.

 

Ok, 1 - do you want your clients to be able to close the browser, and still be logged in? so they dont have to log in every day...

 

OR

 

2- do you want your clients to have to login every time they close the browser? like everyday (or more depending on when they close their browser).

---------

 

this code implies that the cookie in fact only stores the username.

if($_COOKIE['ELv2']) {
$ms = mysql_query("SELECT * FROM `members` WHERE `username`='{$_COOKIE['ELv2']}'");
while($mr = mysql_fetch_array($ms)) {
 	$POINTS = $mr["points"];
 	$MONEY = $mr["money"];
}
}

 

Cookies should either be encrypted with mcrypt functions (php.net/mcrypt) - which is sort of overkill. OR:

 

Use a cookie like "username;md5_of_password", an example would be: "uniflare;fg57h1m3xc055ogj4v3l2aq834bvc72p"

 

all passwords in the db should also be encrypted in case of database compromisation (so hackers could not get every user/pass in ur db, only the md5 'hash' of the password).

------

You would set this cookie like so:

 

$seconds = 3600; // number of seconds until cookie expires. 3600 = 1 hour.
setcookie("loginfo",$username.";".md5($password),time()+$seconds);

http://uk.php.net/setcookie - for more info on setcookie();

 

you would check the login info like so:

 

if(!isset($_SESSION['loggedin']) && isset($_COOKIE['loginfo'])) {
$xploded = explode(";",$_COOKIE['loginfo']); // /the cookie Exists AND there is no session, YET.
$username = $xploded[0];
$password = $xploded[1];

$query = "SELECT * FROM `members` WHERE `username`='$username' AND `password`='$password'";
$result = mysql_query($query) or die("Query Failed<br />".$query."<hr />".mysql_error());
while($row = mysql_fetch_array($result)) {
 	$POINTS = $row["points"];
 	$MONEY = $row["money"];
	$_SESSION['points'] = $POINTS;
	$_SESSION['money'] = $MONEY;
}
}elseif(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true){
$POINTS = $_SESSION['points']; // The cookie does not exist OR the session variable already exists.
$MONEY = $_SESSION['money'];
}else{
exit("Please Login"); // This client has not logged in, no cookie and no sessions.
}

this checks if a session has already been set. - if so then use the session variables

if not then the cookie will be used to login if it exists. - if so then login and set the session variables

if not then the user is told to log in.

 

-------

 

you will need session_start(); at the very top of each page (each and every page, maybe in the index file if you are using one.)

any page without this will not be able to find/use the session for the client.

 

 

hope this helps,

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.