php - 验证用户并重定向到 php 中的登录名或主页
问题描述
我有一个场景,我想在页面加载时验证用户。我希望所有页面都使用相同的脚本,包括登录和主页,如果用户登录重定向到主页,则重定向到登录。在我的代码中,由于重定向太多而失败。需要简单的解决方案。这是我的代码:
会话.php
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', '');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'auth');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
session_start();
$checkId = ''; $checkUser = ''; $checkPass = '';
if(isset($_SESSION['login_userId'])){ $checkId = $_SESSION['login_userId']; };
if(isset($_SESSION['login_userName'])){ $checkUser = $_SESSION['login_userName']; };
if(isset($_SESSION['login_userPass'])){ $checkPass = $_SESSION['login_userPass']; };
$sessionResult = mysqli_query($db, "select * from users where id='$checkId' AND username='$checkUser' AND password='$checkPass'");
$getSessionRow = mysqli_fetch_array($sessionResult, MYSQLI_ASSOC);
$sessionRowcount = mysqli_num_rows($sessionResult);
if(isset($getSessionRow['username']) && $checkUser == $getSessionRow['username']){
header("location:home.php");
}
else {
header("location:login.php");
}
?>
登录.php
<?php
include('session.php');
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login page with login Form</h1>
</body>
</html>
主页.php
<?php
include('session.php');
?>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome to Home page</h1>
</body>
</html>
解决方案
您在两个页面中都使用相同的会话页面,当然它会重定向到很多。您必须从登录和主页中删除会话 php。在登录中单击按钮后创建一个表单,将其发布到会话 php,以便它可以重定向。在顶部的主页 php 中创建一个 if 语句检查会话登录是否已登录,否则将其发送到会话 php 将停止所有循环。