loginBySession

登录实现

记录一次session实现有登录过期时间的登录功能

Login.html

LoginPage

<!DOCTYPE html>  
 <html lang="en">  
 <head>  
 <meta charset="UTF-8">  
 <title>Login</title>  
 </head>  
 <body>  
 <hr size="1">  
 <form action="log.php" method="post" >  
 用户:<input type="text" name="username"/><br>  
 密码:<input type="text" name="password" /><br>  
 <input type="submit" name='login' value="登录">  
 </form>  

Login.php

Login

<?php  
header('content-type:text/html;charset=utf-8');  
//获取表单的用户名和密码  
if ($_SERVER['REQUEST_METHOD'] == 'POST') {  
    if (empty($_POST['username'])){  
        echo "<script>alert('用户名不能为空!');location.href='login.html';</script>";  
    }else {  
        $username=trim($_POST['username']);  
    }  
    if (empty($_POST['password'])){  
        echo "<script>alert('密码不能为空!');location.href='login.html';</script>";  
    }else{  
        $password=$_POST['password'];  
    }  
}  
//连接数据库,查询并返回用户信息  
$link = mysqli_connect('localhost','username','userpassword');  
if(!$link){  
    echo 'connect error!';  
}  
mysqli_select_db($link,'test');  
$sql = "SELECT userpass FROM admin WHERE username="."'$username'";  
$retval = mysqli_query($link,$sql);  
if($retval){  
    $retpass = $retval->fetch_row();  
}else{  
    echo 'sql error!';  
}  
if($retpass){  
    if($password != $retpass[0]){  
        echo "<script>alert('密码错误!');location.href='login.html';</script>";  
    }else{  
        $expire=3600;  
        ini_set('session.gc_maxlifetime',$expire); //初始化PHP session的有效期为一小时  
        //更改php.ini配置文件的值,在脚本生命周期中有效,脚本结束则失效  
        if(empty($_COOKIE['PHPSESSION'])){  
            session_set_cookie_params($expire); //该函数必须在session_start()函数前使用  
            session_start();  
        }else{  
            session_start();  
            setcookie('PHPSESSION',session_id(),time() + $expire);  
        }  
        if(isset($_SESSION['username'])){  
            exit("您已经登入了,请不要重新登入!用户名:{$_SESSION['username']}---<a href='logout.php'>注销</a>");  
        }else{  
            $_SESSION['username']=$username;  
        }  
        echo "<script>alert('登录成功!');</script><br>";  
        echo "您好!{$_SESSION['username']},欢迎回来!";  
        echo "<a href='logout.php'>注销</a>";  
    }  
}else{  
    echo "<script>alert('没有此用户!');location.href='login.html';</script>";  
}  

Logout.php

LoginStatus

<?php  
header('content-type:text/html;charset=utf-8');  
session_start();  
if(isset($_SESSION['username'])){  
    session_unset($_SESSION['username']); //释放所有会话变量  
    session_destroy();  //销毁一个会话的全部数据  
    setcookie(session_name(),''); //销毁保存在客户端 Cookie 中的 Session ID  
    echo "<script>  
    alert('注销成功!');  
    location.href='login.html';  
    </script>";  
}else{  
    echo "<script>  
    alert('注销失败!');  
    </script>";  
}  
-------------本文结束  感谢您的阅读-------------