www.webdeveloper.com
Results 1 to 5 of 5

Thread: Cookies instead of SESSION

  1. #1
    Join Date
    Jul 2011
    Posts
    2

    Cookies instead of SESSION

    I have this login script here:

    PHP Code:
    <?php


    define
    ('INSIDE' true);
    define('INSTALL' false);
    define('LOGIN'   true);
    define('DISABLE_IDENTITY_CHECK'true);
    require_once 
    dirname(__FILE__) .'/common.php';

    includeLang('login');

    if (!empty(
    $_POST)) {
        
    $userData = array(
            
    'username' => mysql_real_escape_string($_POST['username']),
            
    'password' => mysql_real_escape_string($_POST['password'])
        );
        
    $sql =<<<EOF
    SELECT
        users.id,
        users.username,
        users.banaday,
        (CASE WHEN MD5("
    {$userData['password']}")=users.password THEN 1 ELSE 0 END) AS login_success,
        CONCAT((@salt:=MID(MD5(RAND()), 0, 4)), SHA1(CONCAT(users.username, users.password, @salt))) AS login_rememberme
        FROM {{table}}users AS users
            WHERE users.username="
    {$userData['username']}"
            LIMIT 1
    EOF;

        
    $login doquery($sql''true);

        if(
    $login['banaday'] <= time() & $login['banaday'] !='0' ){
            
    doquery("UPDATE {{table}} SET `banaday` = '0', `bana` = '0', `urlaubs_modus` ='0'  WHERE `username` = '".$login['username']."' LIMIT 1;"'users');
            
    doquery("DELETE FROM {{table}} WHERE `who` = '".$login['username']."'",'banned');
        }

        if (
    $login) {
            if (
    intval($login['login_success'])) {
                if (isset(
    $_POST["rememberme"])) {
                    
    setcookie('nova-cookie'serialize(array('id' => $login['id'], 'key' => $login['login_rememberme'])), time() + 2592000);
                }

                
    $sql =<<<EOF
    UPDATE {{table}} AS users
      SET users.onlinetime=UNIX_TIMESTAMP()
      WHERE users.id=
    {$login['id']}
    EOF;
                
    doquery($sql'users');

                
    $_SESSION['user_id'] = $login['id'];
                
    header("Location: overview.php");
                exit(
    0);
            } else {
                
    message($lang['Login_FailPassword'], $lang['Login_Error']);
            }
        } else {
            
    message($lang['Login_FailUser'], $lang['Login_Error']);
        }
    } else {
        
    $parse                 $lang;
        
    $Count                 doquery('SELECT COUNT(DISTINCT users.id) AS `players` FROM {{table}} AS users WHERE users.authlevel < 3''users'true);
        
    $LastPlayer            doquery('SELECT users.`username` FROM {{table}} AS users ORDER BY `register_time` DESC LIMIT 1''users'true);
        
    $parse['last_user']    = $LastPlayer['username'];
        
    $PlayersOnline         doquery("SELECT COUNT(DISTINCT id) AS `onlinenow` FROM {{table}} AS users WHERE `onlinetime` > (UNIX_TIMESTAMP()-900) AND users.authlevel < 3"'users'true);
        
    $parse['online_users'] = $PlayersOnline['onlinenow'];
        
    $parse['users_amount'] = $Count['players'];
        
    $parse['servername']   = $game_config['game_name'];
        
    $parse['forum_url']    = $game_config['forum_url'];
        
    $parse['PasswordLost'] = $lang['PasswordLost'];

        
    $page parsetemplate(gettemplate('login_body'), $parse);

        
    // Test pour prendre le nombre total de joueur et le nombre de joueurs connect�s
        
    if (isset($_GET['ucount']) && $_GET['ucount'] == 1) {
            
    $page $PlayersOnline['onlinenow']."/".$Count['players'];
            die ( 
    $page );
        } else {
            
    display($page$lang['Login']);
        }
    }
    But it only adds a session id which goes away after a short time or if you close the browser, I need to add a cookie that lasts a long time so when they reopen the browser it take them to the right page.

    Posted on daniweb but no one is helping so i thought id try here

    Thankyou!

  2. #2
    Join Date
    Dec 2009
    Location
    City of Smiles
    Posts
    172
    Try changing this:
    PHP Code:
    $_SESSION['user_id'] = $login['id']; 
    to
    PHP Code:
    setcookie("user_id"$login['id'], time()+300); // will expire in 5 mins :) 
    Then try echoing or doing some isset() for $_COOKIE['user_id'] to see the presence of the set cookie.
    Last edited by kingdm; 07-21-2011 at 05:02 AM.
    Can't stand long hours coding in front of computer without being intoxicated.

  3. #3
    Join Date
    Jul 2011
    Posts
    39
    Insted of session in every line of code u can change as cookies.more over u can refer other forum related to that.

  4. #4
    Join Date
    Jul 2011
    Posts
    2
    Thanks... but that didnt work, another file called checkcookies.php could help,


    PHP Code:
    <?php


    function CheckCookies($IsUserChecked)
    {
        global 
    $lang$game_config;

        
    includeLang('cookies');

        
    $userData = array();
        if (isset(
    $_SESSION['user_id'])) {
            
    $sql =<<<EOF
    SELECT * FROM {{table}}
        WHERE id=
    {$_SESSION['user_id']}
        LIMIT 1
    EOF;
            
    $userData doquery($sql'users'true);
        } else if (isset(
    $_COOKIE['nova-cookie'])) {
            
    $cookieData unserialize($_COOKIE['nova-cookie']);
            
    $cookieData = array(
                
    'id' => (isset($cookieData['id']) ? (int) $cookieData['id'] : 0),
                
    'key' => (isset($cookieData['key']) ? (string) $cookieData['key'] : null)
                );

            
    $sql =<<<EOF
    SELECT * FROM {{table}}
        WHERE id=
    {$cookieData['id']}
          AND (@key:=
    {$cookieData['key']})=CONCAT((@salt:=MID(@key, 0, 4)), SHA1(CONCAT(u.username, u.password, @salt))
        LIMIT 1
    EOF;
            
    $userData doquery($sql'users'true);
            
    $_SESSION['user_id'] = $userData['id'];
            if (empty(
    $userData)) {
                
    message($lang['cookies']['Error2'] );
            }
        } else {
            return array(
                
    'state' => false,
                
    'record' => array()
                );
        }

        
    $sessionData = array(
            
    'request_uri' => mysql_real_escape_string($_SERVER['REQUEST_URI']),
            
    'remote_addr' => mysql_real_escape_string($_SERVER['REMOTE_ADDR']/* . (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? '|' . $_SERVER['HTTP_X_FORWARDED_FOR'] : '')*/),
            
    'user_agent' => mysql_real_escape_string($_SERVER['HTTP_USER_AGENT'])
            );
        
    $sql =<<<EOF
    UPDATE {{table}}
        SET `onlinetime` = UNIX_TIMESTAMP(NOW()),
            `current_page` = "
    {$sessionData['request_uri']}",
            `user_lastip` = "
    {$sessionData['remote_addr']}",
            `user_agent` = "
    {$sessionData['user_agent']}"
        WHERE `id`=
    {$_SESSION['user_id']}
        LIMIT 1;
    EOF;
        
    doquery($sql'users');
        
    $IsUserChecked true;

        return array(
            
    'state' => $IsUserChecked,
            
    'record' => $userData
            
    );
    }

    Also in common.php the first line has
    PHP Code:
    session_start(); 
    Thanks

  5. #5
    Join Date
    Jul 2010
    Location
    /ramdisk/
    Posts
    865
    But it only adds a session id which goes away after a short time ....

    a snipper from abstract class User, notice how you can configure the GC probability, the session lifetime and cookie lifetime. Without defining how you want your sessions to behave, PHP will use a default time (something like 21 minutes) which can be incredibly annoying.

    PHP Code:
    Abstract class User {
      private static 
    $session false;

      
    /**
       * Starts the session with the configuration specified in the CONFIG class.
       * @return (bool) True if the session started, otherwise false.
       */
      
    final public static function session_begin() {
        
    DEBUG::SANITY("Attempting to start/restart a session");
        if(
    self::$session) {
           
    DEBUG::SANITY("The session has already started");
           return 
    self::$session === TRUE// continuing will raise an error.
        
    } else {
          
    session_save_path(CONFIG::SESSION_SAVE_PATH);
          
    ini_set('session.name',            CONFIG::SESSION_NAME);
          
    ini_set('session.gc_probability',  CONFIG::SESSION_GC_PROBABILITY);
          
    ini_set('session.gc_maxlifetime',  CONFIG::SESSION_GC_MAX_LIFETIME);
          
    ini_set('session.cookie_lifetime'CONFIG::SESSION_COOKIE_LIFETIME);
          
    ini_set('session.cache_expire',    CONFIG::SESSION_CACHE_EXPIRE);
        }
        
    self::$session session_start();
        
    DEBUG::SANITY(self::$session "Session has started." "Session failed to start!");
        return (bool) 
    self::$session;
      }


    I use (, ; : -) as I please- instead of learning the English language specification: I decided to learn Scheme and Java;

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles