1、connect.inc.php
<?php
define("DSN","mysql:host=localhost;dbname=test");
define("DBUSER","root");
define("DBPWD","playboy");
try{
$pdo=new PDO(DSN,DBUSER,DBPWD);
}catch(PDOException $e){
die("连接失败:'.$e->getMessage());
}
2、login.php
<?php
$session_start();
require "connect.inc.php";
if(isset($_POST['sub'])){
$stmt=$pdo->prepare("select id,username from user where username=? and password=?");
$stmt->execute(array($_POST["username"]),md5($_POST["password"]));
if($stmt->rowcount()>0){
$_SESSION=$stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION["isLogin"]=1;
header("Location:index.php");
}else{
echo '<font color="red">用户名或密码错误!</font>';
}
}
?>
//...注册表单
3、index.php
<?php
session_start();
if(isset($_SESSION['isLogin'])&&$_SESSION['isLogin']===1){
echo "<p>当前用户为:<b>".$_SESSION["username"]."</b>, ";
echo "<a href='loginout.php'>退出</a></p>";
}else{
header("Location:login.php");
exit;
}
//...主页html信息
4、logout.php
<?php
session_strart();
$username=$_SESSION["username"];
$_SESSION=array();
if(issset($_COOKIE[session_name()])){
setcookie(session_name(),'',time()-4200,'/');
}
session_destory();
//...html信息