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 TorontoSoftware DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

gr8gonzoConsultantCommented:
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
Dave BaldwinFixer 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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
APD TorontoSoftware DeveloperAuthor 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
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

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 TorontoSoftware DeveloperAuthor Commented:
Thank you both!
0
Dave BaldwinFixer of ProblemsCommented:
You're welcome!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.