PHP(基本语法)PHP中的Session-登录案例

文件结构:

 

config.php:

<?php
    /**1、数据库服务器 */
    define('DB_HOST','localhost');
    /**2、数据库用户名 */
    define('DB_USER','root');
    /**3、数据库密码 */
    define('DB_PWD','root');
    /**4、数据库名 */
    define('DB_NAME','login');
    /**5、字符集 */
    define('DB_CHARSET','utf8');
?>

 

connection.php:

<?php
    /**1、引入常量配置文件 */
    include './config.php';
    /**2、连接数据库、判断错误、选择库和字符集*/
    $connect = mysqli_connect(DB_HOST,DB_USER,DB_PWD,DB_NAME,'3306');
    if(!$connect){
        exit('连接失败,原因:'.mysqli_error($connect));
    }else{
        echo '连接成功';
    }
    /**设置字符集 */
    mysqli_set_charset($connect,DB_CHARSET);
?>

 

login.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录</title>
</head>
<body>
    <form action="./loginSession.php" method="POST">
        用户名:<input type="text" name="username" id="">
        <hr>
        密码:<input type="password" name="password" id="">
        <hr>
        <input type="submit" value="登录">
    </form>
</body>
</html>

 

loginSession.php:

<?php
    /**连接数据库、选择库、设置字符集 */
    include './connection.php';
    /**开启session */
    session_start();
    /**判断 */
    if(($_POST['username'] !=null ) && ($_POST['password'] != null )) {
        $userName = $_POST['username'];
        $password = $_POST['password'];
        $res = mysqli_query($connect,"select * from user where `username` =  '$userName' ");
        if(!$res){
            printf("Error:%s\n",mysqli_error($connect));
            exit();
        }
        $row = mysqli_fetch_assoc($res);
        if ($row['password'] == $password) {
            /**密码验证通过,设置session,把用户名和密码保存在服务端 */
            $_SESSION['userName'] = $userName;
            $_SESSION['password'] = $password;
            /**最后跳转到登录后的欢迎页面   注意:这里我们没有像cookie一样带参数过去 */
            header('Location: welcome.php');
        }else{
            exit('密码有误');
        }
    }

?>

 

welcome.php: 

<?php
    session_start();
    $userName = $_SESSION['userName'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>欢迎</title>
</head>
<body>
    welcome--你好:<?php echo $userName;?>
</body>
</html>

 

 

 

 

 

.

posted @ 2021-01-18 15:27  剑仙6  阅读(178)  评论(0编辑  收藏  举报
欢迎访问个人网站www.qingchun.在线