数据库配置文件
config.php
<?php
// config.php 数据库连接文件
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '123456');
define('DB_NAME', 'test');
?>
登录首页
login.php
<?php
// login.php 登录界面
require_once('config.php');
session_start();
print_r($_COOKIE);
if(!isset($_SESSION['user_id']))
{
if(isset($_COOKIE['user_id']) && isset($_COOKIE['user_name']))
{
$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['user_name'] = $_COOKIE['user_name'];
setcookie('user_id', $_COOKIE['user_id'], time()+3600, '/');
setcookie('user_name', $_COOKIE['user_name'], time()+3600, '/');
header('Location:face.php');
exit;
}
if(isset($_POST['submit']))
{
$db = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db(DB_NAME, $db);
mysql_query("set names utf8", $db);
// 实际应用中要给加密
$user_name = mysql_real_escape_string(trim($_POST['username']));
$user_pwd = mysql_real_escape_string(trim($_POST['userpwd']));
$sql = "select * from session_cookie where user_name='" . $user_name . "' and userpwd = '" .$user_pwd . "'";
$res = mysql_query($sql, $db);
if(mysql_num_rows($res) == 1)
{
$row = mysql_fetch_assoc($res);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
setcookie('user_id', $row['user_id'], time()+3600, '/');
setcookie('user_name', $row['user_name'], time()+3600, '/');
$url = 'face.php';
header("Location:" . $url);
}else
{
echo '没有相关的用户信息!'; exit;
}
}
}else
{
$url = 'face.php';
header("Location:" . $url);
}
?>
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
user:<input type="text" name="username" /><br />
pwd:<input type="password" name="userpwd" /><br />
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
实际登录的页面
face.php
<?php
// face.php 页面
session_start();
if(!isset($_SESSION['user_id']))
{
if(isset($_COOKIE['user_id']) && isset($_COOKIE['user_name']))
{
$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['user_name'] = $_COOKIE['user_name'];
}else
{
header('Location:login.php');
exit;
}
}
print_r($_SESSION);
?>
<a href="logout.php">退出</a>
登出页面
logout.php
<?php
// 注销 session cookie logout.php
session_start();
if(isset($_SESSION['user_id']))
{
setcookie('user_id', $_SESSION['user_id'], time()-3600, '/');
setcookie('user_name', $_SESSION['user_name'], time()-3600, '/');
session_unset();
session_destroy();
echo '成功退出';
echo '重新登录请login.php';
exit;
}
header('Location:login.php');
?>