[SOLVED] SESSION scope issue.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

bigbunnyboy
Forum Newbie
Posts: 22
Joined: Sat Mar 12, 2005 5:26 am

[SOLVED] SESSION scope issue.

Post by bigbunnyboy »

Hi one and all,
I wonder if someone can help me.
I am putting together a few pages in PHP and MySQL and have run into a little frustration.
I have a page which includes a number of other PHP and HTML pages, for example a header, a footer and a menu.
I want to transfer a login feature into one of the includes, either the header or the menu. So I removed the form data that was present and working in the main page and transferred it into the menu include page as a new include page called login.php. So now I have a nested include structure, are you with me? Please say yes!
So this login page now calls the main page for validation of the data in the database, which works fine and logs in and creates the session variables, hoorah. That is what I thought. Problem is that these session variables are not visible to the menu or header includes.
Why do I want them visible you may ask. For a couple of reasons. In the header there is a piece of welcome text which needs to be modified depending on whether the visitor has logged in. Also, the menu include should no longer display the login details, but should display the fact that the user is logged in and that they should log out if they have finished their session.
Anyhow, no session variables seem to be present when I output the $_SESSION array in any of the include files, but the main index.php shows them up nice and clearly.
Any ideas of why this could be the case?
Any clues are greatly appreciated, I am beginning to go a little mad!
Best regards,
3B
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

One thing... no mater which file you are setting the $_SESSION vars in, you must call session_start() above all other content, so in this case you will probably need to call session_start() at the top of your header.php.

Post some code to clarify things 8)
bigbunnyboy
Forum Newbie
Posts: 22
Joined: Sat Mar 12, 2005 5:26 am

Post by bigbunnyboy »

Hi d11wtq (very cryptic),
I make a call to session_start () at the beginning of the main calling page such as the index.php, as this is the page that calls the includes files. In desperation I have tried placing the session_start () in the includes also, but without any change in circumstance.
I am really confused by this as previously my header file was able to use the variables defined in the main page without a problem, but since I have placed the login in an include this is no longer the case. The thing is that the main page can access the $_SESSION vars.
It really is doing my head in, as I simply cannot get my head around the logic of it!! ARRGGHH!!
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Don't call session_start() multiple times.

Put this code at the very top of index.php

Code: Select all

error_reporting(E_ALL ^ E_NOTICE);
See what errors you get (if any).

Are you trying to call a $_SESSION variable in an include above login.php where the vars haven't been set yet?

It would be more helpful if we could see your code :wink:
User avatar
infolock
DevNet Resident
Posts: 1708
Joined: Wed Sep 25, 2002 7:47 pm

Post by infolock »

should also note that if this code is going to production after you finish debugging, it would be a very good idea to remove that error handling for security reasons. but for debugging, it's the best way to get to the bottom of things...


anyways, to the original poster a simple question :

are you passing the session variables from page to page? or are you simply telling it "session start" and trying to access session data from another page without first passing anything to it?
bigbunnyboy
Forum Newbie
Posts: 22
Joined: Sat Mar 12, 2005 5:26 am

Post by bigbunnyboy »

I have tried inserting the code without any output or differences occurring.
Okay so in regards to the code, please do not laugh at the rudimentary style I use (I am going through my Pascal phase!):

The main page looks something like:

Code: Select all

<?php
session_start();

function checklogin()
{
  include 'includes/config.php';

  $table = "member";

  $arrmember=array(0=>"member_id",1=>"username",2=>"firstname",3=>"familyname",4=>"email");
  $sqlquery = "SELECT member_id,username,firstname,familyname,email FROM member WHERE email = \"".strtolower($_POST["txtMEmail"])."\";";
  $arrmember=queryDB($sqlquery,$arrmember,null);
  
  if ($arrmember[0]["members"]>0)
  {
    $arrmember=array(0=>"member_id",1=>"username",2=>"firstname",3=>"familyname",4=>"email");
    $sqlquery = "SELECT member_id,username,firstname,familyname,email FROM member WHERE email = \"".$_POST["txtMEmail"]."\" AND password = \"".crypt($_POST["txtPassword"], CRYPT_STD_DES)."\";";
    $arrmember=queryDB($sqlquery,$arrmember,null);

    if ($arrmember[0]["members"]>0)
    {
	  $_SESSION['login'] = true;
	  $_SESSION['id'] = $arrmember[0][0];
	  $_SESSION['username'] = $arrmember[0][1];
	  $_SESSION['firstname'] = $arrmember[0][2];
	  $_SESSION['familyname'] = $arrmember[0][3];
	  $_SESSION['email'] = $arrmember[0][4];

	  $sqlupdate="UPDATE member SET logindate=NOW() WHERE member_id=".$_SESSION['id'].";";
	  alterDB($sqlupdate);

      header("Location: ".$_SERVER['HTTP_REFERER']);
	}
	else
	{
//      session_register ("message");
      $_SESSION['message'] = "Password not recognised.  Need a <a href=\"passwordreminder.php\" target=\"_self\" class=\"minibodytext\">reminder</a>?<br>";
      displayloginpage ();
	}
  }
  else
  {
//    session_register ("message");
    $_SESSION['message'] = "Email address ".strtolower($_POST["txtMEmail"])." not recognised.<br>";
    displayloginpage ();
  }
} 

function displayloginpage()
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>mytitle</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="keywords" content="<?php include ('includes/tags.php'); echo $generaltags; ?>">
<meta name="description" content="<?php include ('includes/tags.php'); echo $indexdescription; ?>">
<link href="<?php include ('includes/config.php'); echo CSS_TEMPLATE; ?>fontstyles.css" rel="stylesheet" type="text/css">
</head>
<body>
<table width="100%" border="0" align="center" cellpadding="1" cellspacing="1" id="body" class="bodytext">
  <tr> 
    <td colspan="3" class="menutextinvert">
	  <?php include (CSS_TEMPLATE."header.php"); ?>
	</td>
  </tr>
  <tr> 
    <td width="20%" valign="top"> <?php include (CSS_TEMPLATE."menu.php"); ?> </td>
    <td width="60%" valign="top">
	  <table width="100%" border="0" cellpadding="0" cellspacing="0" class="minibodytext">
	    <tr>
	      <td align="right">home</td>
	      <td width="5%">&nbsp;</td>
	    </tr>
	  </table>
	  <br>
	  <table width="100%" border="0" cellpadding="0" cellspacing="0" class="bodytext">
        <tr> 
          <td colspan="3"> 
              <?php echo "session: ".$_SESSION['username'];
include "includes/includes.php"; include "includes/text.php"; echo LOGIN_WELCOME; ?>
            <p>&nbsp;</p></td>
        </tr>
        <tr> 
          <td width="10%">&nbsp;</td>
          <td width="80%" valign="top">
		    <form action="index.php" method="post" enctype="application/x-www-form-urlencoded" name="frmIndex" target="_self" dir="ltr" lang="en">
              <table width="100%" border="0" cellpadding="0" cellspacing="0" class="minibodytext">
                <tr> 
                  <td class="minibodytextwarning"> 
                    <?php if ($_SESSION['message']!=null) { echo $_SESSION['message']."<br>"; $_SESSION['message']=null;} ?>
                  </td>
                </tr>
              </table>
            </form></td>
          <td width="10%">&nbsp;</td>
        </tr>
        <tr> 
          <td colspan="2">&nbsp;</td>
        </tr>
      </table></td>
    <td width="20%" valign="top"><?php include CSS_TEMPLATE."right.php"; ?></td>
  </tr>
  <tr> 
    <td colspan="3"><?php include CSS_TEMPLATE."footer.htm"; ?> </td>
  </tr>
</table>
</body>
</html>
<?php
}
if ($_SESSION['login']!=null)
{
  header("Location: home.php");
}
else
{
  include 'includes/functions.php';

  if ($_POST["btnSubmit"] == "")
  {
    displayloginpage();
  }
  else
  {
    checklogin();
  }
}
?>
With the menu.php include file looking something like:

Code: Select all

<table width="100%" border="0" cellpadding="1" cellspacing="1" align="center" class="menutext">
  <tr> 
    <td> <table width="80%" border="0" cellpadding="0" cellspacing="0" align="center" class="menutext">
        <tr> 
          <td align="center" class="minibodytext">
            <?php include "login.php"; ?>
		  </td>
        </tr>
      </table></td>
  </tr>
</table>
And the login.php file looking like:

Code: Select all

function displayloginpage()
{
include "../../includes/includes.php";
include "../../includes/text.php";
?>
  
<table width="40%" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr> 
    <td>
	  <form action="index.php" method="post" enctype="application/x-www-form-urlencoded" name="frmLogin" target="_self" dir="ltr" lang="en">
        <table width="100%" border="0" cellpadding="0" cellspacing="0">
          <tr> 
            <td colspan="3" class="minibodytextwarning"> 
              <?php if ($_SESSION["message"]!=null) { echo $_SESSION['message']."<br>"; $_SESSION["message"]=null;} ?>
            </td>
          </tr>
          <tr> 
            <td width="24%" class="smalllogintext"><?php echo $loginstringlabel; ?>:</td>
            <td colspan="2" class="smalllogintext"><input type="text" name="txtMEmail" class="smalllogintext" size="20"></td>
          </tr>
          <tr> 
            <td class="smalllogintext"><?php echo $loginconfirmlabel; ?>:</td>
            <td width="42%" class="smalllogintext"><input type="password" name="txtPassword" class="smalllogintext" size="6"></td>
            <td width="34%" class="smalllogintext"><input name="btnSubmit" type="submit" class="smalllogintext" value="<?php echo $submissionbutton; ?>"></td>
          </tr>
          <tr> 
            <td colspan="3" class="smalllogintext"><div align="center"><a href="register.php" target="_self" class="smalllogintext">Register</a>. 
                Password <a href="passwordreminder.php" target="_self" class="smalllogintext">reminder</a>.</div></td>
          </tr>
        </table>
      </form></td>
  </tr>
</table>
<?php
}

if ($_SESSION['login']!=null)
{
  echo "&nbsp;";
}
else
{
  include '../../includes/functions.php';

  displayloginpage();
}
?>
Is that of any help (once you have stopped laughing!!) and can see clearly through the tears?
I really appreciate your time at looking at this for me you are very kind.
Kind regards,
3B
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Hmmm... can't spot anything obvious.

Did error_reporting(E_ALL ^ E_NOTICE); give you any errors?
bigbunnyboy wrote:...., please do not laugh at the rudimentary style I use (I am going through my Pascal phase!)
Looks nicely laid out to me. Attractive :)
Last edited by Chris Corbyn on Sat Mar 12, 2005 8:36 am, edited 1 time in total.
bigbunnyboy
Forum Newbie
Posts: 22
Joined: Sat Mar 12, 2005 5:26 am

Post by bigbunnyboy »

I popped that code into several places to see if anything happened without anything obvious occurring!!

Maybe I should give up and become a hairdresser!
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: SESSION scope issue.

Post by Chris Corbyn »

bigbunnyboy wrote:Problem is that these session variables are not visible to the menu or header includes.
Have you tried echo()'ing one of the session vars directly in the menu.php file or just in the login.php?
bigbunnyboy
Forum Newbie
Posts: 22
Joined: Sat Mar 12, 2005 5:26 am

Post by bigbunnyboy »

Nothing in menu.php, header.php, login.php!! The session variables have just disappeared!! Maybe I should contact the authorities?
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Try just using

Code: Select all

error_reporting(E_ALL);
Just been told I'm a naughty monkey for turning notices off :lol:
bigbunnyboy
Forum Newbie
Posts: 22
Joined: Sat Mar 12, 2005 5:26 am

Post by bigbunnyboy »

Interesting...
Seems to give me output:
from login.php (after I added session_start () to the file):
Notice: Undefined index: login in /usr/home/magghill/public_html/test/templates/margo_new/login.php on line 44

Notice: Undefined index: message in /usr/home/magghill/public_html/test/templates/margo_new/login.php on line 21
before I added session_start() to the top of the file:
Notice: Undefined variable: _SESSION in /usr/home/magghill/public_html/test/templates/margo_new/login.php on line 44

Notice: Undefined variable: _SESSION in /usr/home/magghill/public_html/test/templates/margo_new/login.php on line 21
and my main file, home.php outputs:
Notice: Constant CSS_TEMPLATE already defined in /usr/home/magghill/public_html/test/includes/config.php on line 2

Notice: Constant SITENAME already defined in /usr/home/magghill/public_html/test/includes/config.php on line 4

etc....
So will any of these be causing the issues?
Thanks for the advice, I feel I moving somewhere, not really too sure where however!!
You may be a naughty monkey, but I am very appreciative of your bad streak!! :)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

sounds like the session variables haven't been set by line 21 and 44 in your login script.

it would appear you include config.php twice or more.. or you truely try to define CSS_TEMPLATE more than once.

Code: Select all

if(!defined('CSS_TEMPLATE'))
{
  define('CSS_TEMPLATE','whatever you set it to');
}
bigbunnyboy
Forum Newbie
Posts: 22
Joined: Sat Mar 12, 2005 5:26 am

Post by bigbunnyboy »

Thanks for the if (!defined) code, it works a treat!

The problem is with the session variables not being set, they are echo'ing to the page from the home page, but not being picked up by the include file. Back to square one!!
Why is the main file able to access the session variables and the includes not? Is this a normal function of PHP? Am I missing something very obvious? Maybe I should get out more!!
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

$_SESSION['login'] is only set in a very specific instance. Since you don't define it for people who are not logged in.. you may want to use isset($_SESSION['login']) instead.
Post Reply