Main Page
<body><? PHP // session_start ();//Open session//http, stateless//session Cookie//session: Stored on the server, each person saves one copy, can store any type of data, the default expiration time of 15 minutes//cookie: Stored on the client, each person save a copy, can only store strings, default never Expires//$_session["UID"] = "Zhangsan";//write Session//echo $_session["UID"];//setcookie ("UID", "Zhangsan"); Set a cookie? ><a href= "test1.php" > Jump </a></body>
Post-Jump page
<body><? PHP // session_start ();//echo $_cookie["UID"];//echo $_session["UID"];? ></body>
Usage examples:
Login Page
<body>
Login Processing Page
<? PHP Session_Start (); include (".. /dbda.php "); $db New Dbda ();
Main Page
<body><? PHP Session_Start (); if (empty($_session["UID"])) // control can not be accessed casually, only after successful login to access other pages { header("location:login.php");} Echo $_session ["UID"];? ></body>
Example two: Add a shopping cart
Show Fruit Information page
<body><table width= "100%" border= "1" cellpadding= "0" cellspacing= "0" ><tr> <td> fruit name </td > <td> Fruit Price </td> <td> fruit Origin </td> <td> Fruit Inventory </td> <td> Action </td>< /tr><?PHPinclude(".. /dbda.php ");$db=NewDbda ();$sql= "SELECT * FROM Fruit";$attr=$db->query ($sql);foreach($attr as $v){ Echo"<tr><td>{$v[1]}</td> <td>{$v[2]}</td> <td>{$v[3]}</td> <td>{$v[4]}</td> <td><a href= ' addgwc.php?code={$v[0]} ' > Add to Cart </a></td></tr> ";}></table><a href= "gouwuche.php" > View shopping Cart </a></body>Fruit Processing page
<?PHPSession_Start();$code=$_get["Code"];//If the first time you clickif(Empty($_session["SG"])){ $attr=Array(Array($code, 1)); $_session["sg"] =$attr;}Else{ //Nth Click, n!=1 $attr=$_session["SG"]; //determine if the fruit division already exists if(Iscunzai ($code)) { foreach($attr as $k=$v) { if($v[0]==$code) { $attr[$k][1] =$v[1]+1; } } $_session["sg"] =$attr; } Else { $arr=Array($code, 1); Array_push($attr,$arr); $_session["sg"] =$attr; }}functionIscunzai ($c){ $attr=$_session["SG"]; $b=false; foreach($attr as $v) { $b=$b||In_array($c,$v); } return $b;}Header("location:showlist.php");
Shopping Cart Page
<body><table width= "100%" border= "1" cellpadding= "0" cellspacing= "0" ><tr> <td> fruit name </td > <td> Fruit Price </td> <td> number of </td></tr><?PHPSession_Start();include(".. /dbda.php ");$db=NewDbda ();$attr=$_session["SG"];foreach($attr as $v){ $sql= "Select Name,price from fruit where ids= ' {$v[0]} ' "; $arr=$db->query ($sql); Echo"<tr><td>{$arr[0][0]}</td> <td>{$arr[0][1]}</td> <td>{$v[1]} </td></tr> ";}?></table></body>$uid=$_post["UID"];$pwd=$_post["PWD"];$sql= "SELECT count (*) from Users where uid= ' {$uid} ' and Pwd = ' {$pwd}‘";$r=$db->strquery ($sql);if($r==1){ $_session["UID"] =$uid; Header("location:main.php");}Else{ Header("location:login.php");}
PHP Session Shopping Cart