php session无法将变量传递给其他页面
问题描述:
I have a formal code, but the session variable can't be passed to another page. So here is my sample code. However, the result of this code is 0.:
page1 code:
<?php
session_start();
$_SESSION['try'] = 5;
header('Location: page2.php');
?>
page2 code:
<?php
session_start();
$test = $_SESSION['try'];
echo $test;
?>
答
From the manual:
session_start() creates a session or resumes the current
one based on a session identifier passed via a GET or POST request,
or passed via a cookie.
pay attention to the last two lines of code:
<?php
// page1.php
session_start();
echo 'Welcome to page #1';
$_SESSION['favcolor'] = 'green';
$_SESSION['animal'] = 'cat';
$_SESSION['time'] = time();
// Works if session cookie was accepted
echo '<br /><a href="page2.php">page 2</a>';
// Or maybe pass along the session id, if needed
echo '<br /><a href="page2.php?' . SID . '">page 2</a>';
?>