這本來是session的基本用法,但在php中就不靈了。不過我們可以把session變數註冊成"跨視窗的全域變數"。但這有一個條件,就是要向需要使用該session變數的視窗發送變數名為session_name(),值為session_id()的變數,用表單或者在url後面用?帶上都可以.並且在使用session變數的頁面的一開始處調用session_start()。
例子如下:
login.php檔案:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>登陸畫面</title>
</head>
<body>
<form action="result.php" method="post">
<table width="100%" border="0">
<tr>
<td align="center" valign="middle"><p>測試系統-----登陸畫面</p>
<table width="250" style="border-collapse:collapse; border-color:#000000"
border="1" cellpadding="2" cellspacing="2">
<tr>
<td width="30%">使用者:</td>
<td><input name="username" type="text" style="width:150px"/></td>
</tr>
<tr>
<td>密碼:</td>
<td><input name="password" type="password" style="width:150px"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="登陸"/></td>
</tr>
</table>
</td>
</tr>
</table>
</form>
</body>
</html>
result.php檔案:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>結果畫面</title>
</head>
<body>
<form method="post">
歡迎你,
<?php
@session_start();
if(isset($_POST["username"])){
$username = htmlspecialchars($_POST["username"]);
$_SESSION[''username''] = $username;
} else {
$username = $_SESSION[''username''];
}
echo $username;
?>
<br/>
<br/>
<a href="login.php">返回</a>
<a href="database.php?".session_name()."=".session_id()."">資料庫測試</a>
</form>
</body>
</html>
database.php檔案:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>結果畫面</title>
</head>
<body>
<form method="post">
Email:
<?php
@session_start();
$conn = mssql_pconnect(''localhost'', ''sa'', ''sa'');
mssql_select_db(''netstore'');
$query = mssql_query(''select * from CUSTOMER'', $conn);
$name = mssql_result($query, 0, ''email'');
echo $name;
?>
<br/>
<br/>
<a href="result.php?".session_name()."=".session_id()."">返回</a>
</form>
</body>
</html>