下面用实例来演示一下如何用cookie和session来实现用户登录:
一、cookie实现用户登录
网站根目录下面有个inc目录,是存放一些公共配置文件的
inc目录下的connect.php是数据库连接文件,代码如下:<?php
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASS','root');
define('DB_NAME','php');
define('DB_CHAR','utf8');
$dbc = mysqli_connect(DB_HOST,DB_USER,DB_PASS);
if(mysqli_connect_errno($dbc)){
echo '连接失败'.mysqli_connect_error($dbc);
}
mysqli_select_db($dbc,DB_NAME);
mysqli_set_charset($dbc,DB_CHAR);
inc目录下的function.php是公共函数库,封装了一些常用方法<?php
//公共函数库
/*
*用户自定义跳转地址
*/
function redirect_user($page = 'index.php')
{
$url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
$url = rtrim($url,'/\\');
$url .= '/'.$page;
header('Location:'.$url);
exit();
}
/*
*验证用户登录
*/
function check_login($dbc,$email='',$password='')
{
$errors = [];
//验证邮箱
if(empty($email)){
$errors[]='邮箱地址不能为空';
}else{
$e = mysqli_real_escape_string($dbc,trim($email));
}
//验证密码
if(empty($password)){
$errors[] = '密码不能为空';
}else{
$p = mysqli_real_escape_string($dbc,trim($password));
}
//非空验证通过
if(empty($errors)){
$sql = "SELECT `user_id`,`user_name` FROM `user` WHERE `email`='$e' AND `password`=sha1('$p')";
$res = mysqli_query($dbc,$sql);
if(mysqli_num_rows($res)==1){
$row = mysqli_fetch_array($res,MYSQLI_ASSOC);
return[true,$row];
}else{
$errors[]='邮箱和密码不正确,请重新输入';
}
}
return[false,$errors];
}
inc目录下有个header.php,是网站的头部文件,代码如下:html>
<?php echo isset($page_title) ? $page_title : '默认标题'; ?>Toggle navigation
Brand
- 首页 (current)
- Link
Submit
- <?php if((isset($_COOKIE['user_id']))&&basename($_SERVER['PHP_SELF'])!='logout.php'){
echo '退出';
}else{
echo '登录';