PHP中如何为不同用户类的用户使用session并处理登录页跳转问题
问题根因
你代码最开头校验三类用户session的逻辑执行时,还没有调用session_start()启动会话,PHP无法读取已存在的会话数据,因此所有isset()判断均返回false,不会触发跳转逻辑。你仅在登录提交的分支里启动了会话,仅处理了提交登录请求的场景,没有覆盖直接访问登录页的场景。
修正方案
- 将
session_start()放在PHP代码的最开头,所有逻辑执行之前,确保访问登录页时就能读取到已有的会话信息 - 移除各个登录分支中重复的
session_start(),避免重复启动会话抛出错误
修正后完整代码
<?php // 最开头启动会话 session_start(); if(isset($_SESSION['p_login'])){ header("location:login_tests/Patient.php"); exit; // 跳转后加exit终止后续代码执行,避免逻辑异常 } else if(isset($_SESSION['d_login'])){ header("location:login_tests/Doctor.php"); exit; } else if(isset($_SESSION['a_login'])){ header("location:admin/Dashboard.php"); exit; } // 登录功能 if(isset($_POST['submit1'])){ // 患者登录 if($_POST['users']=="patient"){ include_once 'classes/patient.php'; $patient = new Patient(); if ($patient->p_session()) { header("location:login_tests/Patient.php"); exit; } $patient = new Patient(); if ($_SERVER["REQUEST_METHOD"] == "POST"){ $login = $patient->p_login($_REQUEST['username'],$_REQUEST['password']); if($login){ header("location:login_tests/Patient.php"); exit; } else { echo "<script>alert('登录失败!');</script>"; } } } // 医生登录 else if($_POST['users']=="doctor"){ include_once 'classes/doctor.php'; $doctor = new Doctor(); if ($doctor->d_session()) { header("location:login_tests/Doctor.php"); exit; } $doctor = new Doctor(); if ($_SERVER["REQUEST_METHOD"] == "POST"){ $login = $doctor->d_login($_REQUEST['username'],$_REQUEST['password']); if($login){ header("location:login_tests/Doctor.php"); exit; } else { echo "<script>alert('登录失败!');</script>"; } } } // 管理员登录 else{ include_once 'classes/admin.php'; $admin = new Admin(); if ($admin->a_session()) { header("location:admin/Dashboard.php"); exit; } $admin = new Admin(); if ($_SERVER["REQUEST_METHOD"] == "POST"){ $login = $admin->a_login($_REQUEST['username'],$_REQUEST['password']); if($login){ header("location:admin/Dashboard.php"); exit; } else { echo "<script>alert('登录失败!');</script>"; } } } } // 注册功能 else if(isset($_POST['submit2'])){ include_once 'classes/patient.php'; $patient = new Patient(); if ($_SERVER["REQUEST_METHOD"] == "POST"){ $register = $patient->p_register($_REQUEST['name'],$_REQUEST['gender'], $_REQUEST['dob'], $_REQUEST['nic'], $_REQUEST['address'],$_REQUEST['email'], $_REQUEST['username'], $_REQUEST['password']); if($register){ echo "<script>alert('注册成功!');</script>"; } else { echo "<script>alert('输入的邮箱地址或用户名已存在!');</script>"; } } } ?>
额外优化说明
- 所有
header跳转后加exit/die是通用规范,可避免跳转后后续代码仍执行导致的逻辑异常 - 注册分支如果后续需要操作会话,可直接复用顶部已经启动的会话,不需要额外调用
session_start()
内容的提问来源于stack exchange,提问作者learning Gatherer
相关产品推荐
相关产品推荐

