PHP Login Script Does Not Hold

Hi Experts,

I am building a small application, but upon successfull login I am trying to store information in $_SESSION. I am managed to replicate the behaviour in the below prototype.

index.php
<?php
    if (isset($_SESSION)){
        session_destroy();
        unset($_SESSION);
    }

    if (session_start() == FALSE) {    
        $error = 'Please enable cookies, then refresh this page.'
                . '<br><br> This error must be resolved before logging in.';
    } 
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <a href="login.php">Click Here To Login</a>
    </body>
</html>

Open in new window


login.php
<?php

    $env['domain'] = '192.168.2.200';
    
     logout(); //destroy previous sessions.
    $lifetime = 60 * 60 * 24; // 24h in seconds
    session_set_cookie_params($lifetime, '/', $env['domain'], TRUE, FALSE);
    session_start();
    
    $user = array();
    $user['id'] = 1;
    $user['name'] = 'John';
    
    $_SESSION['user'] = $user;
    
    header('Location: result.php');

    function logout(){
        
        
        //Destroy Session
        if (isset($_SESSION)){
            session_destroy();
            unset($_SESSION);
        }

        //Delete Sess cookie
        $name = session_name();
        $expire = strtotime('-1 year');
        $params = session_get_cookie_params();
        $path = $params['path'];
        $domain = $params['domain'];
        $secure = $params['secure'];
        $httponly = $params['httponly'];

        setcookie($name, '', $expire, $path, $domain, $secure, $httponly);

        
    }
    
?>

Open in new window


result.php
<?php
session_start();
print_variable($_SESSION, 'sess');

function print_variable($var, $label, $raw = true){

    echo '<br>=========START=========<br>';
    echo '<b>' . $label . '</b>';

    if ($raw == true) echo '<pre>';

    print_r($var);

    if ($raw == true) echo '</pre>';
    echo '<br>=========END=========<br>';
}
?>

Open in new window


Result Output
=========START=========
sess
Array
(
)

=========END=========

Open in new window


However, from login.php, I did store $user in $_SESSION, why it is not storing and outputing it in result.php?

I have another php application that is on the same server that is storing session data, so I dont think it is my server.

Any help will be greatly appreciated.
APD TorontoAsked:
Who is Participating?
 
Dave BaldwinConnect With a Mentor Fixer of ProblemsCommented:
"session_start()" must almost ALWAYS be the first line on all pages involving SESSIONS.  Even  session_destroy() will not work properly if "session_start()" isn't before.  "session_start()" either creates or restores the session identified with the browser.  Without it, session_destroy() will not know what session to destroy.  Without it, isset($_SESSION) is meaningless.

There is almost NEVER a reason to explicitly expire a session cookie.  The code in Example #1 on this page http://php.net/manual/en/function.session-destroy.php is the proper way to destroy a session and it's cookie.  That will also perform your logout function.
0
 
gr8gonzoConnect With a Mentor ConsultantCommented:
Well, first, this line will probably throw a warning:
    $env['domain'] = '192.168.2.200';

Open in new window

...because it seems to be the very first line in the page, and at that point, $env isn't going to be defined.

So if it DOES provide any warnings or ANY output at all before you start the session, then your session will not initialize properly. The session_start() should be one of the first lines in your code - before ANY output (even white space / blank lines). As soon as there's ANY output content at all, PHP figures you're done with all the HTTP header modifications (including cookie work).

Second, this probably isn't your issue now, but whenever you have a line like this:    
    header('Location: result.php');

Open in new window

You should always follow it with an exit() or a die() line in order to prevent PHP from processing anything further in the page.
1
 
APD TorontoAuthor Commented:
I cannot try this until later today, but if I start login.php as follows

<?php
session_start();
$env = array ();
//the rest of the code

Open in new window


From my original code, do I still keep lines 8, 23, etc...?
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
gr8gonzoConsultantCommented:
you only need to do session_start() once.

You can leave the session_destroy in your logout() function.

In your index file, you also seem to be destroying the session - not sure why, but you might want to remove that code.
0
 
Dave BaldwinFixer of ProblemsCommented:
you only need to do session_start() once.
On each page...
1
 
Dave BaldwinFixer of ProblemsCommented:
You probably need to rewrite much of 'login.php'.  The 'logout' procedure needs to follow the example on http://php.net/manual/en/function.session-destroy.php .

I see that you are trying to extend the 'time-out' for the sessions.  You might be able to do that on your private server.  On shared hosting where there can be 100+ users, the shortest time out always 'wins' because they are all using common code because they are all using common code to run PHP.  That is normally the standard 24 minutes / 1440 seconds.  

Note that that is for a period of inactivity.  A user who is continuously active can stay logged in indefinitely.  At least until the server is rebooted.  Most of the hosting companies I use reboot the servers every day between 3AM and 5AM.
0
 
gr8gonzoConsultantCommented:
"On each page..."
Oops, yeah. Sorry, wasn't really thinking about how that might be interpreted. :)
0
 
APD TorontoAuthor Commented:
Thank you both!
0
 
Dave BaldwinFixer of ProblemsCommented:
You're welcome!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.