tags:

views:

28

answers:

1

At it's simplest, if file_1.php contains

<?php

  session_start(); 

  $_SESSION["test_message"] = "Hello, world";

  header("Location: http://localhost/file_2.php");
?>

and file_2.php contains

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"&gt;
<html>
<head>
</head>
<body>

<?php

  if (!(isset($_SESSION["test_message"])))
    echo "Test message is not set";
  else
    echo $_SESSION["test_message"];

var_dump($_SESSION);

  session_destroy();
?>

</body>
</html>

the result is Test message is not set and a var_dump($_SESSION) returns null - locally, with Xampp. However, if I upload those same files to a paid-for hosted web site, it works and I see

Hello, world
array
  'test_message' => string 'Hello, world' (length=12)

When I look at PHPinfo under Xampp it shows Session Support enabled. What am I doing wrong?

+2  A: 

You've forgotten the session_start at the top of file_2.php

So it should be:

<?php
session_start(); 
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"&gt;
<html>
<head>
</head>
<body>

<?php

  if (!(isset($_SESSION["test_message"])))
    echo "Test message is not set";
  else
    echo $_SESSION["test_message"];

var_dump($_SESSION);

  session_destroy();
?>

</body>
</html>

session_start() should be at the top of every file where you need to access the session functions.

EDIT:

You should really use session_write_close before redirecting to another page.

first file:

<?php
session_start(); 

$_SESSION["test_message"] = "Hello, world";

session_write_close(); 
header("Location: http://localhost/file_2.php");
?>
Kieran Allen
session_start(); at the top of file_2? Why not the start of file_1? That's where the session starts and it sets the session variable which fiel_2 will retrieve.
Mawg
It has to be in both scripts. session_start() does *not* initialize a _new_ session, it starts php's session handling mechanism which you have to do (at least) once in each instance of php you want to use the session data in. New request, new instance of php, new session_start().
VolkerK
ok, it two of you say so - I've +1 you both. BUT it still doesn't work
Mawg
just edited my post.
Kieran Allen
+1 Thanks. I have updated the question to reflect this. I am just about to upload teh files to my own web server, rather than use Xampp on my laptop, to see if it might make adifference
Mawg
aargh! When I upload it to my hosted web site it works, but does nto work when I run it locally in Xamp.
Mawg
oops, now it also works locally. I will guess that session_write_close(); did it and was just cached which made me think that it failed. Thanks for your help, Kieran !
Mawg