SESSION实战
1.connect.php
实例
<?php $db=[ 'type'=>'mysql', 'host'=>'localhost', 'dbname'=>'test2', 'user'=>'root', 'pw'=>'root' ]; $dsn="{$db['type']}:={$db['host']};dbname={$db['dbname']}"; try{ $pdo=new PDO($dsn,$db['user'],$db['pw']); }catch (PDOException $a){ die( '链接错误' .$a->getMessage()); }
运行实例 »
点击 "运行实例" 按钮查看在线实例
PHP手写代码:
2.index.php
实例
<?php session_start(); if (isset($_SESSION['name'])) { echo '用户: ' . $_SESSION['name'] . '已登录<br>'; echo '<a href="dispatch.php?action=logout">退出</a>'; } else { echo '<a href="dispatch.php?action=login">请登录</a>'; }
运行实例 »
点击 "运行实例" 按钮查看在线实例
PHP手写代码:
3.dispatch.php
实例
<?php session_start(); require __DIR__ .'/connect.php'; $action=isset($_GET['action'])?$_GET['action']:'login'; $action=htmlentities(strtolower(trim($action))); switch ($action){ case 'login': include __DIR__ .'/login.php'; break; case 'check': include __DIR__ .'/check.php'; break; case 'logout': include __DIR__ .'/logout.php'; break; default: header('Location:index.php'); echo '<script>location.assign("index.php");</script>'; }
运行实例 »
点击 "运行实例" 按钮查看在线实例
PHP手写代码:
4.login.php
实例
<?php session_start(); if (isset($_SESSION['name'])) { echo '<script>alert("请不要重复登录");location.assign("index.php");</script>'; } ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>用户登录</title> </head> <body> <h3>用户登录</h3> <form action="dispatch.php?action=check" method="post"> <p> <label for="phone">手机号:</label> <input type="text" name="phone" id="phone"> </p> <p> <label for="password">密码:</label> <input type="password" name="password" id="password"> </p> <p> <button>提交</button> </p> </form> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例
PHP手写代码:
5.check.php
实例
<?php session_start(); if ($_SERVER['REQUEST_METHOD'] === 'POST') { $phone = $_POST['phone']; $password = md5($_POST['password']); $sql = 'SELECT * FROM user WHERE phone = :phone AND pwd = :password LIMIT 1'; $stmt = $pdo->prepare($sql); $stmt->execute(['phone'=>$phone,'password'=>$password]); $user = $stmt->fetch(PDO::FETCH_ASSOC); print_r($user); if ($user === false) { echo '<script>alert("验证失败");history.back();</script>'; die; } $_SESSION['name']=$user['name']; echo '<script>alert("登录成功");location.assign("index.php");</script>'; exit; } else { die('请求类型错误'); }
运行实例 »
点击 "运行实例" 按钮查看在线实例
PHP手写代码:
6.logout.php
实例
<?php if (isset($_SESSION['name'])) { session_destroy(); echo '<script>alert("退出成功");location.assign("index.php");</script>'; } else { echo '<script>alert("请先登录");location.assign("login.php");</script>'; }
运行实例 »
点击 "运行实例" 按钮查看在线实例
PHP手写代码: