tree em
tree em

Reputation: 21751

Help me with Php session vs Header redirect?

I have the following pages:

page1.php

<?php 
if (isset($_GET['link'])) { 
session_start(); 
$_session['myvariable'] = 'Hello World'; 
header('Location: http://' . $_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']) . '/page2.php'); 
exit; 
} 
?> 
<a href="<?php print $_SERVER['REQUEST_URI'] . '?link=yes';?>">Click Here</a>

page2.php

<?php 
print 'Here is page two, and my session variable: '; 
session_start(); 
print $_session['myvariable']; //This line could not output.
exit; 
?>

When I try output $_session['myvariable'] I did not get the result hello world message.

I could not find out the solution to fix it?

Upvotes: 0

Views: 253

Answers (3)

Amy B
Amy B

Reputation: 17977

<?php 
session_start(); 
echo $_SESSION['myvariable'];

echo 'Here is page two, and my session variable: '; 
exit;
?>

HTTP headers must be the very first output, so session_start() must be at the top of your code.

Other notes: * $_SESSION should be uppercase. * Echo > print

Upvotes: 1

Neil Aitken
Neil Aitken

Reputation: 7854

session_start() has to be called before you send any output as it relies upon cookies to store the ID.

Also $_SESSION is uppercase

Upvotes: 1

Your Common Sense
Your Common Sense

Reputation: 157872

$_SESSION not $_session. Uppercase.

error_reporting(E_ALL); at the top of the script always helps in such case

Upvotes: 4

Related Questions