SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Zealot
    Join Date
    Mar 2006
    Posts
    139
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    session_set_save_handler not working

    Hello all,
    i am having troubles handling sessions using some custom functions. However when i use session_set_save handler to handle the session storages, these functions do not seem to be called. Is there anything that I am missing here?

  2. #2
    SitePoint Evangelist hexburner's Avatar
    Join Date
    Jan 2007
    Location
    Belgium
    Posts
    591
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It could be numerous things, code would be nice.
    FOR SALE: 1 set of morals, never used, will sell cheap

  3. #3
    SitePoint Zealot
    Join Date
    Mar 2006
    Posts
    139
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    hi, thanks for the quick response. I am only using the mail functions to check whether or not these functions are called . And I am using the session_set_save_handler to call these functions.

  4. #4
    SitePoint Evangelist hexburner's Avatar
    Join Date
    Jan 2007
    Location
    Belgium
    Posts
    591
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That's not the information I was looking for, but I got something here for you:
    I posted this once here on Sitepoint: a session handler that works!

    PHP Code:
     <?
        
    /**
         *    A simple session handler
         *
         *    @class            Session
         *    @date            27-02-2007
         *    @author            Vincent Verbruggen
         *
         *    First read all the comments please.
         *
         *    Usage (safest way):
         *        Session::useCustomHandler();
         *        Session::Start();
         *        Session::Register("myName", "Vincent Verbruggen");
         *
         *    Or:
         *        Session::useCustomHandler();
         *        session_start();
         *        session_register("myName", "Vincent Verbruggen")
         */
        
        /**
         *    Define some constants so you can handle everything yourself.
         *    The save path is relative to this file.
         */
        
    define("__SESSION_SAVE_PATH__"realpath(dirname(__FILE__))."/Temp"true);
        
    define("__SESSION_GC_MAX_LIFETIME__"3600true);
        
    define("__SESSION_GC_PROBABILITY__"1true);
        
    define("__SESSION_GC_DIVISOR__"100true);
        
        class 
    Session
        
    {
            
    /**
             *    Start the session
             */
            
    function Start()
            {
                
    session_start();
            }
            
            
    /**
             *    Destroy the session
             */
            
    function Destroy()
            {
                
    session_destroy();
                
    $_SESSION $HTTP_SESSION_VARS = array();
                
    session_unset();
                
            }
            
            
    /**
             *    Set parameters for the cookie to be stored at the client side
             *
             *    @param integer $lifetime            The lifetime of the cookie in seconds
             *    @param string $path                    The path to which the cookie will apply to
             *    @param string $domain                The domain to which the cookie will apply to
             *    @param boolean $secure                For Secure HTTP (HTTPS)
             */
            
    function setCookieParams($lifetime$path=NULL$domain=NULL$secure=false)
            {
                
    session_set_cookie_params ($lifetime$path$domain$secure);
            }
            
            
    /**
             *    Register a new session variable
             *
             *    @param mixed $name                    The name of the session variable
             *    @param mixed $value                    The value to be stored in the session variable
             */
            
    function Register($name$value="")
            {
                if ( !
    Session::isRegistered ($name) ){
                    
    session_register($name);
                    
    $_SESSION[$name] = $HTTP_SESSION_VARS[$name] = $value;
                }
                else {
                    
    Session::setValue($name$value);
                }
            }
            
            
    /**
             *    Unregister a session variable
             *
             *    @param mixed $name                    The name of the session variable
             */
            
    function Unregister ($name)
            {
                if ( 
    Session::isRegistered($name) ){
                    
    session_unregister($name);
                }
            }
            
            
    /**
             *    Check if a session variable is registered
             *
             *    @param mixed $name                    The name of the session variable
             *    @return boolean                        True if the session variable exists, false otherwise
             */
            
    function isRegistered ($name)
            {
                return ( isset( 
    $_SESSION[$name] ) ? true : ( isset( $HTTP_SESSION_VARS[$name] ) ? true false ) );
            }
            
            
    /**
             *    Get the value of a session variable
             *
             *    @param mixed $name                    The name of the session variable
             *    @return mixed                        The value of the session variable
             */
            
    function getValue ($name)
            {
                return ( 
    Session::isRegistered($name) ? ( isset( $_SESSION[$name] ) ? $_SESSION[$name] : $HTTP_SESSION_VARS[$name] ): NULL );
            }
            
            
    /**
             *    Set the value of a session variable
             *    @param mixed $name                    The name of the session variable
             *    @param mixed $value                    The value to be stored in the session variable
             */
            
    function setValue ($name$value)
            {
                if ( 
    Session::isRegistered ($name) ){
                    
    $_SESSION[$name] = $HTTP_SESSION_VARS[$name] = $value;
                }
            }
            
            
    /**
             *    Set the maximum lifetime for session files in the Garbage Collection
             *    This function will only work when you use the custom session handler,
             *    and must be called before calling Session::useCustomHandler();
             *    You can only use this function once in a script!
             *    
             *    @param integer $expire                The lifetime of the session files in seconds
             */
            
    function setGCMaxLifetime ($expire)
            {
                if ( !
    defined("__SESSION_CUSTOM_GC_MAX_LIFETIME__") ){
                    
    session_cache_limiter ("private");
                    
    session_cache_expire ($expire);
                    
    define("__SESSION_CUSTOM_GC_MAX_LIFETIME__"$expire);
                }
            }
            
            
    /**
             *    Set the probability for the Garbage Collection.
             *    This function will only work when you use the custom session handler,
             *    and must be called before calling Session::useCustomHandler();
             *    The chance the Garbage Collection is cleaned is equal to (Probability / Divisor)
             */
            
    function setGCProbability ($probability)
            {
                if ( !
    defined("__SESSION_CUSTOM_GC_PROBABILITY__") ){
                    
    define("__SESSION_CUSTOM_GC_PROBABILITY__"$probability);
                }
            }
            
            
    /**
             *    Set the divisor for the Garbage Collection.
             *    This function will only work when you use the custom session handler,
             *    and must be called before calling Session::useCustomHandler();
             *    The chance the Garbage Collection is cleaned is equal to (Probability / Divisor)
             */
            
    function setGCDivisor ($divisor)
            {
                if ( !
    defined("__SESSION_CUSTOM_GC_DIVISOR__") ){
                    
    define("__SESSION_CUSTOM_GC_DIVISOR__"$divisor);
                }
            }
            
            
    /**
             *    Set the path to save the session files to.
             *    This function will only work when you use the custom session handler,
             *    and must be called before calling Session::useCustomHandler();
             *    You can only use this function once in a script!
             */
            
    function setSavePath ($savePath)
            {
                
    define("__SESSION_CUSTOM_SAVE_PATH__"realpath(dirname(__FILE__)).$savePath);
            }
            
            
    /**
             *    Set the custom session handler to handle the sessions.
             *    This function has to be called before Session::Start(); and can only
             *    be called once in a script!
             */
            
    function useCustomHandler ()
            {
                
    session_save_pathrealpath( ( defined("__SESSION_CUSTOM_SAVE_PATH__") ? __SESSION_CUSTOM_SAVE_PATH__ __SESSION_SAVE_PATH__ ) ) );
                
    session_set_save_handler("_Open""_Close""_Read""_Write""_Destroy""_DummyGarbageCollection");
                
                
    session_cache_limiter ("private");
                if ( 
    defined"__SESSION_CUSTOM_GC_MAX_LIFETIME__" ) ){
                    
    session_cache_expire (__SESSION_CUSTOM_GC_MAX_LIFETIME__);
                }
                else {
                    
    session_cache_expire (__SESSION_GC_MAX_LIFETIME__);
                }
            }
        }

        
    ################################################################################
        #                                                                              #
        #     Below you'll find the functions used for the custom session handler.     #
        #                                                                              #
        ################################################################################
        
        /**
         *    Function called right before a new session starts
         */
        
    function _Open ($savePath$name)
        {
            
    # Initialize the custom variables for the custom session handler
            
    define("__USE_CUSTOM_SESSION_HANDLER__"truetrue);
            
    define("__SESSION_CURRENT_SAVE_PATH__"$savePathtrue);
            
    define("__SESSION_CURRENT_NAME__"$nametrue);
            
    define("__SESSION_CURRENT_GC_MAX_LIFETIME__", ( defined("__SESSION_CUSTOM_GC_MAX_LIFETIME__") ? "__SESSION_CUSTOM_GC_MAX_LIFETIME__" __SESSION_GC_MAX_LIFETIME__), true);
            
    define("__SESSION_CURRENT_GC_PROBABILITY__", ( defined("__SESSION_CUSTOM_GC_PROBABILITY__") ? "__SESSION_CUSTOM_GC_PROBABILITY__" __SESSION_GC_PROBABILITY__), true);
            
    define("__SESSION_CURRENT_GC_DIVISOR__", ( defined("__SESSION_CUSTOM_GC_DIVISOR__") ? "__SESSION_CUSTOM_GC_DIVISOR__" __SESSION_GC_DIVISOR__), true);
            
            
    # Emulate the Garbage Collection
            
    _GarbageCollection();
            
            return 
    true;
        }
        
        
    /**
         *    Function called right before the session is closed
         */
        
    function _Close ()
        {
            return 
    true;
        }
        
        
    /**
         *    Function to add or subtract time from another time.
         *    Used in function _Read
         */
        
    function addTime ($format="Y-m-d H:i:s"$datetime=NULL$add=NULL$unit="hours")
        {
            
    $add = ( $add $add );
            
    $timestamp strtotime( ($datetime $datetime date($format) ));
            return 
    date($formatstrtotime($add.$unit$timestamp));
        }
        
        
    /**
         *    Function to read the information from the session file
         */
        
    function _Read ($sessionId)
        {
            
    $sessionFile __SESSION_CURRENT_SAVE_PATH__ "/sess_" $sessionId;
            
            if (!
    file_exists($sessionFile)){
                
    $resource = @fopen($sessionFile'wb');
                
    fclose($resource);
            }
            
            
    $fileatime date("Y-m-d H:i:s"fileatime($sessionFile) );
            
    $expiry addTime("Y-m-d H:i:s"date("Y-m-d H:i:s"), -__SESSION_CURRENT_GC_MAX_LIFETIME__"seconds");
                    
            
    $sessionData "";
            if ( 
    $fileatime $expiry ){
                
    _Destroy ($sessionId);
            }
            else {
                
    $sessionData file_get_contents($sessionFile);
                
    touch($sessionFile);
            }
            
            return ( empty(
    $sessionData) ? "" $sessionData );
        }
        
        
    /**
         *    Function used to write to the session file
         */
        
    function _Write ($sessionId$sessionData)
        {
            
    $sessionFile __SESSION_CURRENT_SAVE_PATH__ "/sess_" $sessionId;
            
            if (
    $resource = @fopen$sessionFile"w")) {
                return(
    fwrite($resource$sessionData));
            }
            else {
                return 
    false;
            }
        }
        
        
    /**
         *    Function called right before the session is destroyed
         */
        
    function _Destroy ($sessionId)
        {
            
    $sessionFile __SESSION_CURRENT_SAVE_PATH__ "/sess_" $sessionId;
            if ( 
    file_exists($sessionFile) ){
                
    unlink($sessionFile);
            }
            return 
    true;
        }
        
        
    /**
         *    Function to manage the Garbage Collection, in other words: files that
         *    are older than the set gc_maxlifetime will be removed.
         */
        
    function _GarbageCollection ($gcMaxLifeTime=__SESSION_GC_MAX_LIFETIME__)
        {
            
    # Calculate the probability to clean up the directory where the session files are stored
            
    $chance rand(1,__SESSION_CURRENT_GC_DIVISOR__);
            
    $found false;
            for (
    $i 0$i __SESSION_CURRENT_GC_PROBABILITY__$i++){
                if ( 
    $chance == rand(1,__SESSION_CURRENT_GC_DIVISOR__) ){
                    
    $found true;
                }
            }
            
            if (
    $found){
                
    # Ignore the original lifetime of the garbage collection from the server settings
                # Choose the lifetime set in systems.ini instead
                
    $gcMaxLifetime __SESSION_CURRENT_GC_MAX_LIFETIME__;
                
                
    $directory __SESSION_CURRENT_SAVE_PATH__;
                if (
    $dir = @opendir($directory) ) {
                    while ((
    $file readdir($dir)) !== false) {
                        if (
    $file != '.' && $file != '..'){
                            if (
    $file != "sess_" session_id() && (time() - fileatime$directory."/".$file ) ) > $gcMaxLifetime){
                                @
    unlink $directory."/".$file );
                            }
                        }
                    }
                    
    closedir($dir);
                }
            }
            
            return;    
        }
         
        
    /**
         *    Dummy function for the Garbage Collection. In order to control GC_DIVISOR
         *    and GC_PROBABILITY we need to have the possibility to define that too.
         */
        
    function _DummyGarbageCollection ($gcMaxLifetime=__SESSION_GC_MAX_LIFETIME__)
        {
            return 
    true;
        }
    ?>
    FOR SALE: 1 set of morals, never used, will sell cheap

  5. #5
    SitePoint Zealot
    Join Date
    Mar 2006
    Posts
    139
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    this is the code i am using right now.

    PHP Code:
    <?php
    define
    ('AUTO_MAIL','pragyaratna@exmple.com');
    function 
    open($save_path$session_name
    {
     
    mail (AUTO_MAIL,'session oppened','session opened');
     return(
    true);
    }

    function 
    close() 
    {

     return(
    true);
    }

    function 
    read($id
    {
     
    mail (AUTO_MAIL,'session read done','session read ');

    }

    function 
    write($id$sess_data
    {
    mail (AUTO_MAIL,'session write','inside session write');
    }

    function 
    destroy($id
    {
    mail (AUTO_MAIL,'session destroyed','session destroyed');
    }


    function 
    gc($maxlifetime
    {
        
    mail (AUTO_MAIL,'session garbage','garbage collected');
     return 
    true;
    }

    session_set_save_handler("open""close""read""write""destroy""gc");

    session_start();
    mail (AUTO_MAIL,'session tests','check all ');



    ?>
    Is it the case that the php.ini variable session.save_handler has to be changed to some other values? If so, what values can be assigned to this?

    the problem is that none of these functions are being called presently.

  6. #6
    SitePoint Evangelist hexburner's Avatar
    Join Date
    Jan 2007
    Location
    Belgium
    Posts
    591
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Works fine with me.
    First check if the session handler is accepted:
    PHP Code:
    if (session_set_save_handler('open''close''read''write''destroy''gc')) {
        die(
    'Works fine');
    }
    else {
        die(
    'Couldn\'t set session handler');

    FOR SALE: 1 set of morals, never used, will sell cheap

  7. #7
    SitePoint Zealot
    Join Date
    Mar 2006
    Posts
    139
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    hi hexburner,
    thanks for the help so far. Just went through the vars set in php.ini and found that the variable session.save_handler was set to a default value of "files".

    I changed it to "user" using ini_set() and now it seems to be working fine.

    Once again thanks for your help.


Bookmarks

Posting Permissions

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