Page 1 of 1

Trouble with Sessions and file locations

Posted: Thu Dec 14, 2006 12:36 pm
by giles
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Hi all,

I’m working on my first project with sessions, kind of getting stuck on what is probably a simple point. Would you mind correcting me? My understanding is that I can declare the session variables in an include file such as

Code: Select all

<?php
  if (!isset($_SESSION["count"]))
  {
    $_SESSION["start"] = time();
    $_SESSION["count"] = 1;
	$_SESSION["counthistory"] = 1;
	$_SESSION["lastpage"] = 100;
  }
  $_SESSION["count"]++;
?>
and that I can then access the session from other files such as :

Code: Select all

<?php  
require_once "admin.inc";
session_start();
echo "session_id() is : " . session_id();
echo "</br>";
echo $_SESSION["count"];
?>
this is partly working, in that I can return the session_id, but I get a “Undefined index: count” with the count parameter. what am I doing wrong?

I’d appreciate any help you could give me.
Thanks in advance
Giles


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Thu Dec 14, 2006 1:13 pm
by Begby
You have to call session_start() before using anything with $_SESSION. The problem you are having is you are including your admin.inc file before calling session_start().

Posted: Thu Dec 14, 2006 5:24 pm
by giles
thanks for the quick response ... works a treat!

guess the only thing leaving me a little puzzled is why do ALL the tutorials I've been working on put the include files at the top seemingly without getting into trouble? I thought I needed to put a reference to the file where I have the session variables before I try use them?

G

Posted: Thu Dec 14, 2006 6:31 pm
by Begby
Yes, you need to include the file before you try to access the session variables, but you need to call session_start() before you do anything with sessions at all.

When you include a file, think of it as copying all the code out of the file and pasting it into where the include is.