[英]Check user activity in php login site
我想检查用户是否已经登录,例如用户是否已经登录,然后再次打开登录链接,应该在索引页面上重定向他,但我的问题是,我在登录站点中有 php 代码,而我的php 登录站点不显示,我无法登录。
<?php
session_start(); //start session.
if(!isset($_SESSION['User_id']) && $_SESSION['User_id'] == ""){
header('Location: ../users/login.php?error=5'); //redirect URL
}
else{
header('Location: ../users/index.php?error=6'); //session gestartet
}
?>
index.php 直接打开错误,返回登录站点,正常
<?
php session_start();
if(!isset($_SESSION['User_id'])){
$host = $_SERVER['HTTP_HOST'];
$extra = '../users/login.php?error5'; // direct access error
header("Location: http://$host/$extra"); }
?>
您可能会遇到重定向循环,因此您的逻辑可能不合理,正如其他用户在此行中所指出的那样:
if(!isset($_SESSION['User_id']) && $_SESSION['User_id'] == ""){
我想您可能在其他地方也有类似的行,特别是如果您说您已将此行更改为使用||
而不是&&
。
我会说使用函数(或类/方法)使您的脚本更具人类可读性会很有帮助,因此它更易于使用并保持一致,这只是一个示例:
/functions.php
<?php
# Have a simple function to determine login state
function isLoggedIn()
{
# Since $_SESSION['User_id'] must be filled to be logged in, empty() is the simplest
# and best to use here because it takes care of isset() and == '' at the same time
return (!empty($_SESSION['User_id']));
}
# Have a redirect function so you know it's going to be consistent
function redirect($to)
{
header('Location: '.$to);
exit;
}
# Maybe a site url is helpful
function baseUrl($path = false)
{
return 'http://'.str_replace('//', '/', $_SERVER['HTTP_HOST'].'/'.$path);
}
/restricted_page.php
<?php
session_start();
# Add the functions
include(realpath(__DIR__.'/..').'/functions.php');
# If the user is not logged in
if(!isLoggedIn()) {
# Redirect them to the login page
redirect(baseUrl('users/login.php?error=5'));
}
/users/login.php
<?php
session_start();
# Add the functions
include(realpath(__DIR__.'/..').'/functions.php');
# If the user is logged in already
if(isLoggedIn()) {
# Redirect home since they don't need to log in again
redirect(baseUrl());
}
假设索引页面是中性的,它不应该重定向到任何地方。 如果您的登录页面发布到不同的页面以检查凭据,它将类似于:
/users/process_login.php
<?php
session_start();
# Add the functions
include(realpath(__DIR__.'/..').'/functions.php');
# Check if the login has been submitted
if(empty($_POST['submit'])) {
# Go back to login page if not
redirect('users/login.php?error=7');
}
# Do your checking with whatever login code you use...
// code here...
# Check if the user is logged in now
if($success) {
# Redirect to success page
$page = 'success.php';
}
else {
# Redirect back to login with failure msg
$page = 'users/login.php?error=5';
}
# Redirect
redirect($page);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.