Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 13 of 13
  1. #1
    Regular Coder
    Join Date
    Feb 2010
    Posts
    209
    Thanks
    15
    Thanked 2 Times in 2 Posts

    Can someone explain this PHP script?

    Here is the script:
    PHP Code:
    <?php
    function regenerateSession($reload false)
    {
        
    // This token is used by forms to prevent cross site forgery attempts
        
    if(!isset($_SESSION['nonce']) || $reload)
            
    $_SESSION['nonce'] = md5(microtime(true));

        if(!isset(
    $_SESSION['IPaddress']) || $reload)
            
    $_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];

        if(!isset(
    $_SESSION['userAgent']) || $reload)
            
    $_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];

        
    //$_SESSION['user_id'] = $this->user->getId();

        // Set current session to expire in 1 minute
        
    $_SESSION['OBSOLETE'] = true;
        
    $_SESSION['EXPIRES'] = time() + 60;

        
    // Create new session without destroying the old one
        
    session_regenerate_id(false);

        
    // Grab current session ID and close both sessions to allow other scripts to use them
        
    $newSession session_id();
        
    session_write_close();

        
    // Set session ID to the new one, and start it back up again
        
    session_id($newSession);
        
    session_start();

        
    // Don't want this one to expire
        
    unset($_SESSION['OBSOLETE']);
        unset(
    $_SESSION['EXPIRES']);
    }

    function 
    checkSession()
    {
        try{
            if(
    $_SESSION['OBSOLETE'] && ($_SESSION['EXPIRES'] < time()))
                throw new 
    Exception('Attempt to use expired session.');

            if(!
    is_numeric($_SESSION['user_id']))
                throw new 
    Exception('No session started.');

            if(
    $_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR'])
                throw new 
    Exception('IP Address mixmatch (possible session hijacking attempt).');

            if(
    $_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT'])
                throw new 
    Exception('Useragent mixmatch (possible session hijacking attempt).');

            if(!
    $this->loadUser($_SESSION['user_id']))
                throw new 
    Exception('Attempted to log in user that does not exist with ID: ' $_SESSION['user_id']);

            if(!
    $_SESSION['OBSOLETE'] && mt_rand(1100) == 1)
            {
                
    $this->regenerateSession();
            }

            return 
    true;

        }catch(
    Exception $e){
            return 
    false;
        }
    }

    ?>
    as you can see - this is script for sessions... What I have to change to use it into my website?

    Thanks in advance...

  • #2
    Senior Coder
    Join Date
    Jun 2008
    Location
    New Jersey
    Posts
    2,546
    Thanks
    45
    Thanked 259 Times in 256 Posts
    The first function looks like its made to create more "secure" sessions, while the second looks like its to test if the session is set, but they look like they might be part of a class? At least the second one? Remove the $this-> and i don't see why it shouldn't work?

    And there's no way we could know what you need to change to use it on your site... we don't know whats on your site, what you wanna do, etc. So... yah...

  • #3
    Regular Coder
    Join Date
    Feb 2010
    Posts
    209
    Thanks
    15
    Thanked 2 Times in 2 Posts
    PHP Code:
    <?php 
    function regenerateSession($reload false

        
    // This token is used by forms to prevent cross site forgery attempts 
        
    if(!isset($_SESSION['nonce']) || $reload
            
    $_SESSION['nonce'] = md5(microtime(true)); 

        if(!isset(
    $_SESSION['IPaddress']) || $reload
            
    $_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR']; 

        if(!isset(
    $_SESSION['userAgent']) || $reload
            
    $_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT']; 

        
    //$_SESSION['user_id'] = user->getId(); 

        // Set current session to expire in 1 minute 
        
    $_SESSION['OBSOLETE'] = true
        
    $_SESSION['EXPIRES'] = time() + 60

        
    // Create new session without destroying the old one 
        
    session_regenerate_id(false); 

        
    // Grab current session ID and close both sessions to allow other scripts to use them 
        
    $newSession session_id(); 
        
    session_write_close(); 

        
    // Set session ID to the new one, and start it back up again 
        
    session_id($newSession); 
        
    session_start(); 

        
    // Don't want this one to expire 
        
    unset($_SESSION['OBSOLETE']); 
        unset(
    $_SESSION['EXPIRES']); 


    function 
    checkSession() 

        try{ 
            if(
    $_SESSION['OBSOLETE'] && ($_SESSION['EXPIRES'] < time())) 
                throw new 
    Exception('Attempt to use expired session.'); 

            if(!
    is_numeric($_SESSION['user_id'])) 
                throw new 
    Exception('No session started.'); 

            if(
    $_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR']) 
                throw new 
    Exception('IP Address mixmatch (possible session hijacking attempt).'); 

            if(
    $_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT']) 
                throw new 
    Exception('Useragent mixmatch (possible session hijacking attempt).'); 

            if(!
    loadUser($_SESSION['user_id'])) 
                throw new 
    Exception('Attempted to log in user that does not exist with ID: ' $_SESSION['user_id']); 

            if(!
    $_SESSION['OBSOLETE'] && mt_rand(1100) == 1
            { 
                
    regenerateSession(); 
            } 

            return 
    true

        }catch(
    Exception $e){ 
            return 
    false
        } 

    ?>
    Like this? What is more, I would like to add $_SESSION['authID'] = $r['userid'];... Where in the script should I add it?

    But this script does not create session? It just checks it?

  • #4
    New Coder
    Join Date
    Jun 2009
    Location
    Manipal
    Posts
    45
    Thanks
    2
    Thanked 3 Times in 3 Posts
    Could you be more specific as to what you want ?

  • #5
    Regular Coder
    Join Date
    Feb 2010
    Posts
    209
    Thanks
    15
    Thanked 2 Times in 2 Posts
    I want to keep one variable in this session... Like name.

  • #6
    Senior Coder
    Join Date
    Jun 2008
    Location
    New Jersey
    Posts
    2,546
    Thanks
    45
    Thanked 259 Times in 256 Posts
    Why do you need either of those functions do to that?

    Start a session, store the variable in the session, done? Neither function destroys sessions... they simply regenerate them, randomly changing the ID (for some reason?). There's no reason you can't just store w/e variables you want and use them as usual.

    The purpose of using those functions is whats confusing us... why do you wanna use that? What is your aim/goal? It seems like added work without much gain unless you're super intent on security, in which case, you're better off understanding that function then simply using it. For example, what is the loadUser function? What class does this come from?
    Last edited by Keleth; 06-24-2010 at 06:39 PM.

  • #7
    Regular Coder
    Join Date
    Feb 2010
    Posts
    209
    Thanks
    15
    Thanked 2 Times in 2 Posts
    OK, there is my login page:
    I use simple PHP sessions, but I want to increase security to my session... Who can update my script?
    PHP Code:
    <?php
    if(isset($_POST['enter'])) {
    include 
    $_SERVER['DOCUMENT_ROOT'] . '/connect/db_conn.php';
        
    $password md5($_POST['password']);
        
    $nick $_POST['nick'];
        
        
    $password mysql_real_escape_string($password);
        
    $nick mysql_real_escape_string($nick);
        
    $nick strtolower($nick);

    if(
    $password == '') {
            
    $error .= "<li>Enter your password!</li>";
        }
        if(
    $nick == '') {
            
    $error .= "<li>Enter your Nick!</li>";
        }    
            if(
    preg_match('/\W/'$password)) {
            
    $error .= "<li>!!! No symbols !!!</li>";
            } else {
            if(
    preg_match('/\W/'$nick)) {
            
    $error .= "<li>!!! No symbols !!!</li>";}}    

    $check mysql_query("SELECT * FROM `test_sessions` WHERE nick='$nick' AND pass='$password'") or die(mysql_error());
        if(
    mysql_num_rows($check) == 0) {
            
    $error .= "<li>Wrong password or Nick!</li>";
        }

        if(isset(
    $error)) {
            
    $eroras '<center><font color="grey">Mistakes:<br/><br/><font color="blue">'.$error.'</font></center>';
        } else {
            
            
    $r mysql_fetch_array$check ) or die(mysql_error());
            
                
    session_start();
                
                
    $code md5($nick.$password);
                
    $sess_time=date('ymdHis');
                
    $sess_browser=$_SERVER['HTTP_USER_AGENT'];
                
                
    $_SESSION['code'] = $code;
                
    $_SESSION['time'] = $sess_time;
                
    $_SESSION['browser'] = $sess_browser;
            
            
    header("Location: index.php"); 
        }

    if(
    $_GET['act'] == 'logout') {
        
    session_start(); // begin session
        
    session_unset();
        
    session_destroy(); // remove the entire session
    }     
    }
    ?>
    <?php 
    echo "$eroras";?>

    <html xmlns="http://www.w3.org/1999/xhtml" lang="lt">
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta http-equiv="Content-Language" content="lt"/>
    </head>
    <body>
    <form method='post' action='login[test].php'>
    <table align='center'><tr><td> User:</td>
    <br />
    <td><input type='text' name='nick' size='15'></td>
    </tr><tr><td>Password:</td>
    <br />
    <td><input type='password' name='password' size='15'><input type='submit' name='enter' value=' Enter '></td></tr></table>
    <br />
    </form>
    </body>
    </html>
    This is just login page. Do I have to validate user in other pages and how?

    Thanks for your time spending on this...

  • #8
    Senior Coder
    Join Date
    Jun 2008
    Location
    New Jersey
    Posts
    2,546
    Thanks
    45
    Thanked 259 Times in 256 Posts
    How I've done it in the past to increase security is I store a cookie with some data (like userID, username, etc) and a session variable that contains an encrypted string of the last login date/time with a seed variable.

    Then on each page, I check to see if the data matches up with the encrypted string. So someone trying to sneak their way in would need userID, username, (some other internal data) as well as the extract seed variable I use, where I use it, etc... odds are low.

  • #9
    Regular Coder
    Join Date
    Feb 2010
    Posts
    209
    Thanks
    15
    Thanked 2 Times in 2 Posts
    Quote Originally Posted by Keleth View Post
    How I've done it in the past to increase security is I store a cookie with some data (like userID, username, etc) and a session variable that contains an encrypted string of the last login date/time with a seed variable.

    Then on each page, I check to see if the data matches up with the encrypted string. So someone trying to sneak their way in would need userID, username, (some other internal data) as well as the extract seed variable I use, where I use it, etc... odds are low.
    I don't know much about cookies... How make them work with PHP? Could you update my script? I also use md5 code which is stored as $_SESSION['code']

  • #10
    Senior Coder
    Join Date
    Jun 2008
    Location
    New Jersey
    Posts
    2,546
    Thanks
    45
    Thanked 259 Times in 256 Posts
    Well, its not a case of updating, I wouldn't use your code at all. Cookies are easy to work with in PHP:

    http://www.w3schools.com/php/php_cookies.asp

  • #11
    Regular Coder
    Join Date
    Feb 2010
    Posts
    209
    Thanks
    15
    Thanked 2 Times in 2 Posts
    I wouldn't use your code at all
    Why you wouldn't?

  • #12
    Senior Coder
    Join Date
    Jun 2008
    Location
    New Jersey
    Posts
    2,546
    Thanks
    45
    Thanked 259 Times in 256 Posts
    Well... the code I use has its own security features, why use the second set of security features you're using? The method I proposed would be instead of the code you're looking at.

  • #13
    Regular Coder
    Join Date
    Feb 2010
    Posts
    209
    Thanks
    15
    Thanked 2 Times in 2 Posts
    What I have to do is?:
    0. Do I have to FORCE Cookies?
    1. Create a cookie like
    PHP Code:
    <?php
    $hash 
    md5($nick.$password.$time);
    setcookie("hash""$hash");
    ?>
    2. Use it as $_COOKIE['hash'] in PHP?
    3. Where I should put this code?

    The part of session which I am trying to create is:
    PHP Code:
     session_start(); 
                 
                
    $code md5($nick.$password); 
                
    $sess_time=date('ymdHis'); 
                
    $sess_browser=$_SERVER['HTTP_USER_AGENT']; 
                 
                
    $_SESSION['code'] = $code
                
    $_SESSION['time'] = $sess_time
                
    $_SESSION['browser'] = $sess_browser
    For now, I am not looking further(checking and regenerating the session_id or other encrypted codes). Now, I want to change this to create powerful session...
    Last edited by auriaks; 06-24-2010 at 10:42 PM.


  •  

    Posting Permissions

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