p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   PHP How-To (http://p2p.wrox.com/forumdisplay.php?f=98)
-   -   Constantly losing PHP session variable? (http://p2p.wrox.com/showthread.php?t=20449)

achalasia October 27th, 2004 01:48 AM

Constantly losing PHP session variable?
 
Hi there,

I'm pretty new to PHP, but had a friend help me with fixing up my basic code. I've got a website which has a login feature, and we've FINALLY got the login and logout working, using the session variable and calling to a database of members. The home page is called "index.php", and when a user logs in, the only information that changes is the welcome message up the top, but they're still on the same page.

The problem occurs AFTER you log in. If you do any of the following, the website destroys the session variable and returns you to 'Guest' status:

1. Refresh the page (index.php) - by manually clicking in the address bar and hitting Enter again.
2. Click on any link that has a href value of "index.php" (e.g. the 'Home' link on the navigation bar, or the store logo in the corner of the page).

We've used the following two lines of code to DELIBERATELY erase the session:

$_SESSION = array();
session_destroy();

... in ONLY two places. Firstly, what I'll call the logout clause (where the user has logged in and then clicks the logout button). Secondly, before the user logs in again - it's set to wipe the session to ensure that they're starting from scratch, then resets all session variables.

We've echoed different error messages all over the place to determine how it's destroying the session, and it's not going to EITHER of those places mentioned above.

Is this - the spontaneous destruction of a session upon renavigating to a page that has a login script in it, after logging in - a peculiarity with PHP, or is there something wrong with our code? (I'd put it in here, but there's a whole lot of unnecessary HTML stuff that'd take too long to remove.)

On the technical side, I'm using the following:

- Apache 2.0.52
- MySQL 4.0.21
- PHP 4.3.9

Would really appreciate feedback ASAP, this project is due next week. 0_o;;

Thanks!

~Bec


imaginethis October 27th, 2004 11:23 AM

It might do us some good if we could see what you are talking about. :-) Please post the code for your index.php page. It sound's like you need to seperate the session_destroy function within an if statement like so:
if(login){
  $_SESSION = array();
}
if(logout){
  session_destory();
}

YOu may try something similar to this method or paste some code for further assistance.

<>_<>

achalasia October 28th, 2004 07:32 PM

The following is the PHP code at the start and the HTML for the form - I've removed everything else.

<?php
session_start();
header("Cache-control: private");

include 'global_variables.php';

if($_POST['process'])
{
    $muname = $_POST['username'];
    $mpass = $_POST['password'];

    $usname = addslashes($muname);
    $paword = addslashes($mpass);

    $connection = mysql_connect("$dbhost","$dbusername","$dbpasswd")
        or die ('Couldn\'t connect to server.');
    $db = mysql_select_db("$database_name", $connection)
        or die('Couldn\'t select database.');

    $query = "SELECT memberno, givenname FROM member WHERE UPPER(username) = UPPER('$usname') AND UPPER(password) = UPPER('$paword')";

    $result = mysql_query($query) or die ('Query failed');
    $num_result = mysql_num_rows($result);

    if($num_result==1)
    {
        $_SESSION = array();
        session_destroy();

        $row = mysql_fetch_array($result);
        $_SESSION['memberno'] = ($row['memberno']);
        $_SESSION['givenname'] = ($row['givenname']);
        $_SESSION['username'] = $muname;
        $_SESSION['password'] = $mpass;

        $errormsg = $errormsg."none";
    }
    else
    {
        $errormsg = "Please enter a valid username and password.";
    }
}

if($_POST['logout'])
{
    $_SESSION = array();
    session_destroy();

    $errormsg = $errormsg."logout";
}

if((!isset($_SESSION['username']))||(!isset($_SESSION['password'])))
{
    $muname = 'guest';
    $mpass = 'none';
    $mgname = 'Guest';

    $errormsg = $errormsg."guest";
}
else
{
    $muname = $_SESSION['username'];
    $mpass = $_SESSION['password'];
    $mgname = $_SESSION['givenname'];

    $errormsg = $errormsg."user";
}

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title>Welcome To <?php echo htmlspecialchars($companyName) ?>!</title>

    <script language="JavaScript" type="text/javascript">
    <!--
    <!--

    <!--
    <!-- hide
    function validLogin(the_form)
    {
        if (the_form.username.value == "")
        {
            alert("You must enter a username.")
            the_form.username.focus()
            return false
        }
        if (the_form.password.value == "")
        {
            alert("You must enter a password.")
            the_form.password.focus()
            return false
        }
        return true
    }

    function subLogin()
    {
        if (validLogin(document.frm_login))
        {
            document.frm_login.submit()
        }
    }

    function subLogout()
    {
        document.frm_login.submit()
    }

    //-->
    </script>
</head>


<body style="background-color: rgb(0, 0, 0);">
<center>



    <form name="frm_login" method="post" action="index.php">
    <?php
        if(!$_SESSION['username'])
        {
    ?>
            <div style="float:left">
            <img src="images/spacer.gif" width="40" height="1" border="0">
            <span style="font-size: 9pt; color: rgb(204, 204, 204); font-family: arial; letter-spacing: 2px;"><b>U: </b></span>
            <input type="text" name="username" id="username" maxlength="10" size="20">
            <img src="images/spacer.gif" width="21" height="1" border="0">
            <span style="font-size: 9pt; color: rgb(204, 204, 204); font-family: arial; letter-spacing: 2px;"><b>P: </b></span>
            <input name="password" type="password" id="password" size="20" maxlength="10">
            <img src="images/spacer.gif" width="15" height="1" border="0">
            </div>
            <div style="float:right">
            <a href="javascript:subLogin()"><img src="images/login_button.jpg" alt="Login" name="btn_login" border="0"></a>
            </div>
            <input type="hidden" name="process" id="process" value="1">
    <?php
        }
        else
        {
    ?>
            <input type="hidden" name="logout" id="logout" value="1">
            <div style="float:left">
            <img src="images/spacer.gif" width="60" height="1" border="0">
            <span style="font-size: 9pt; color: rgb(204, 204, 204); font-family: arial; letter-spacing: 2px;">You are logged in.</span>
            </div>
            <div style="float:right">
            <a href="javascript:subLogout()"><img src="images/logout_button.jpg" alt="Logout" name="btn_logout" border="0"></a>
            </div>
    <?php
        }
    ?>
</form>

</center>
</body>
</html>



achalasia October 29th, 2004 09:08 AM

Just letting y'all know it's been sorted.

Dunno why it didn't occur to me earlier, but forgot to start a new session after the session_destroy call in the 'process' block, so it wasn't paying attention to the session settings saved afterwards.

Thanks!



All times are GMT -4. The time now is 07:54 PM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.