SESSION的作用很多,最多用的就是站點內頁面間變量傳遞。在頁面開始我們要session_start();開啟SESSION;
然後就可以使用SESSION變量了,比如說要賦值就是:$_SESSION['item']="item1";要得到值就是$item1=$_SESSION['item'];,很簡單吧。這裡我們可能會使用到一些函數,比如說判斷是不是某SESSION變量為空,可以這麼寫:empty($_SESSION['inum'])返回true or false。
下面綜合一下前面所說的我們來看一個登陸程序,判斷用戶名密碼是否正確。
登陸表單是這樣:login.php
<table width="100%" height="100%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<form action="checklogin.php" method="post"><td align="center" valign="middle"><table width="400" border="0" cellpadding="5" cellspacing="1" class="tablebg">
<tr class="tdbg">
<td colspan="2"><div align="center">Administrators Login</div></td>
</tr>
<tr class="tdbg">
<td><div align="center">Username</div></td>
<td><div align="center">
<input name="username" type="text" id="username">
</div></td>
</tr>
<tr class="tdbg">
<td><div align="center">Password</div></td>
<td><div align="center">
<input name="password" type="password" id="password">
</div></td>
</tr>
<tr class="tdbg">
<td colspan="2"><div align="center">
<input type="submit" name="Submit" value="Submit">
<input type="reset" name="Submit2" value="Clear">
</div></td>
</tr>
</table></td></form>
</tr>
</table>
處理文件是這樣
<?
require_once('conn.php');
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
$exec="select * from admin where username='".$username."'";
if($result=mysql_query($exec))
{
if($rs=mysql_fetch_object($result))
{
if($rs->password==$password)
{
$_SESSION['adminname']=$username;
header("location:index.php");
}
else
{
echo "<script>alert('Password Check Error!');location.href='login.php';</script>";
}
}
else
{
echo "<script>alert('Username Check Error!');location.href='login.php';</script>";
}
}
else
{
echo "<script>alert('Database Connection Error!');location.href='login.php';</script>";
}
?>
conn.php是這樣:
<?
$conn=mysql_connect ("127.0.0.1", "", "");
mysql_select_db("shop");
?>
由於 $_SESSION['adminname']=$username;我們可以這樣寫驗證是否登陸語句的文件:checkadmin.asp
<?
session_start();
if($_SESSION['adminname']=='')
{
echo "<script>alert('Please Login First');location.href='login.php';</script>";
}
?>