Wrox Programmer Forums
Go Back   Wrox Programmer Forums > PHP/MySQL > PHP How-To
| Search | Today's Posts | Mark Forums Read
PHP How-To Post your "How do I do this with PHP?" questions here.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the PHP How-To section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
  #1 (permalink)  
Old May 1st, 2006, 01:05 PM
Authorized User
 
Join Date: Apr 2006
Location: bikaner, raj, India.
Posts: 19
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via Yahoo to chayanvinayak
Default only one login allowed at a time using one userid

What will be the script for allowing only single login at a time using one userid.

ie. one person can login from only one site/machine(only once) at a time using his/her userid.

constraint : user should not be locked for ever is he/she get disconnected abnormally.

i have used following concept but it permanently lock the user if he gets abnormally disconnected.


when user login : log= 1
whe user logout : log=0

chayan vinayak goswami
__________________
chayan vinayak goswami
  #2 (permalink)  
Old May 1st, 2006, 01:39 PM
richard.york's Avatar
Wrox Author
Points: 5,506, Level: 31
Points: 5,506, Level: 31 Points: 5,506, Level: 31 Points: 5,506, Level: 31
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: Camby, IN, USA.
Posts: 1,706
Thanks: 0
Thanked 6 Times in 6 Posts
Default

Basically, you need some custom session management.

http://www.php.net/session

It's possible, for instance, to store all of your session data in a database.

Then it would be trivial to query the database for the existence of a session, and find out if a user is logged in.

Say I have a session variable like this:

$_SESSION['USER_ID']

If this variable exists, then I know a login is active for that user. The session data itself is stored in a flat text file by default, but, I can set up a custom session handler using PHP's session_set_save_handler() function. Text files aren't very efficient to query, so I can set up sessions to be stored in a database.

My own custom session handler looks something like this:
Code:
<?php

class session {

    public static function setHandler()
    {
        session_set_save_handler(
            array('session', 'open'),
            array('session', 'close'),
            array('session', 'read'),
            array('session', 'write'),
            array('session', 'destroy'),
            array('session', 'garbageCollection')
        );
    }

    public static function open($save_path, $session_name)
    {
        return true;
    }

    public static function close()
    {
        return true;
    }

    public static function read($session_id)
    {
        $query = db::query(
            "SELECT `session_data`
               FROM `sessions`
              WHERE `session_id` = '{$session_id}'
              LIMIT 1"
        );

        return(
            (db::numRows($query))?
                stripslashes(db::result($query))
            :
                null
        );
    }

    public static function write($session_id, $session_data)
    {
        if (db::numRows("SELECT * FROM `sessions` WHERE `session_id` = '{$session_id}'"))
        {
            db::query(
                "UPDATE `sessions`
                    SET `session_data`  = '".addslashes($session_data)."',
                        `last_accessed` = NOW()
                  WHERE `session_id`    = '{$session_id}'"
            );
        }
        else
        {
            db::query(
                "INSERT
                   INTO `sessions`
                 VALUES (
                     '{$session_id}',
                     '".addslashes($session_data)."',
                     NOW()
                 )"
            );
        }
    }

    public static function destroy($session_id)
    {
        db::query(
            "DELETE
               FROM `sessions`
              WHERE `session_id` = '{$session_id}'"
        );
    }

    public static function garbageCollection($lifetime)
    {
        db::query(
            "DELETE
               FROM `sessions`
              WHERE UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(`last_accessed`) > {$lifetime}"
        );
    }

    public static function name()
    {
        return session_name();
    }

    public static function id()
    {
        return session_id();
    }
}
?>
To use that, you'd call session::setHandler(); before calling session_start();

You'd also need PHP 5 to use my code verbatim, but it'd be trivial to make it work with PHP 4, just remove "public static" from before each of the function definitions.

That goes with the following MySQL database:
Code:
CREATE TABLE `sessions` (
  `session_id` varchar(50) NOT NULL default '',
  `session_data` text NOT NULL,
  `last_accessed` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
  PRIMARY KEY  (`session_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
If I want to find out if a user is already logged in, I'd do a query like this:
Code:
$query = db::query(
    "SELECT `session_id` 
       FROM `sessions`
      WHERE `session_data` LIKE '%\"USER_ID\";s:".strlen($user_id).":\"{$user_id}\"%'
      LIMIT 1"
);
If I get a hit, the user already has an active session.

The last thing you want to do is to increase garbage collection probability, otherwise a session could get stuck in an active state and the user could potentially get locked out of their account.

You'll want to tweak the following two INI directives:
session.gc_probability AND session.gc_maxlifetime

More information about those directives is available at http://www.php.net/session

HTH!

Regards,
Rich

--
Author,
Beginning CSS: Cascading Style Sheets For Web Design
CSS Instant Results

http://www.catb.org/~esr/faqs/smart-questions.html
  #3 (permalink)  
Old May 1st, 2006, 01:54 PM
Authorized User
 
Join Date: Apr 2006
Location: bikaner, raj, India.
Posts: 19
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via Yahoo to chayanvinayak
Default

using your concept i used following script , but i work only for single explorer i.e. when user login using new-window of explorer it lets the user login.

<?php
mysql_connect ("localhost", "game_cvg", "cvg") or die ('cannot connect : ' . mysql_error());
mysql_select_db("game_accounts") or die ('cannot select database because: ' . mysql_error());
session_start();
$userid = $_GET['$userid'];
$password = $_GET['$password'];

if($_SESSION[logged]<>1){
  echo 'you are now logged in';
  $_SESSION[logged]=1;
}
else
echo 'You are already loggedin';

?>

chayan vinayak goswami


Similar Threads
Thread Thread Starter Forum Replies Last Post
Funky - Login Failed for user 'Domain\UserId' erro jnks2005 ASP.NET 2.0 Basics 5 February 26th, 2007 01:38 PM
question about login and "remember me next time" hertendreef ASP.NET 2.0 Professional 0 February 14th, 2007 07:29 AM
single user login at a time dayarprasad MySQL 1 June 23rd, 2006 11:08 PM
UserId/Computer Name mrookey Dreamweaver (all versions) 1 August 2nd, 2005 11:47 AM
UserId/Computer Name mrookey SQL Server ASP 1 August 2nd, 2005 07:23 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.