[英]If session exists redirect to other page PHP
我有 index.php 和 home.php 頁面。 index.php 就像登錄頁面,但如果用戶已登錄或會話存在,我想將他從 index.php 重定向到 home.php,如果他嘗試訪問 index.php。 代碼的重定向部分位於 header.php 中,它是包含在 home.php 和 index.php 中的代碼的一部分。 問題是我認為我陷入了重定向循環, ERR_TOO_MANY_REDIRECTS
這是我得到的錯誤。 我想我需要說如果這是 home.php 停止重定向,但我不知道該怎么做
這是我在 header.php 中的代碼
<?php include('database.php');
session_start();
if(isset($_SESSION['id'])) {
header('Location: home.php');
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
home.php 代碼
<?php include('header.php'); ?>
<?php include('nav.php'); ?>
<?php include('footer.php'); ?>
index.php 代碼
<?php include 'header.php';?>
<?php include 'nav.php';?>
//Some code not relevant to question
<?php include 'footer.php';?>
正如許多其他人所說,你最終陷入了無限循環
您可以像這樣解決它,在用戶需要登錄的頁面上的標題之前定義例如 RESTRICTED
主頁.php:
<?php
define( 'RESTRICTED', true );
require( 'header.php' );
// etc
?>
索引.php:
<?php
require( 'header.php' );
// etc
?>
和標題:
include('database.php');
session_start();
if ( defined( 'RESTRICTED' ) ) {
if ( !isset( $_SESSION['id'] ) ) {
header( 'Location: index.php' );
exit();
}
}
else {
if ( isset( $_SESSION['id'] ) ) {
header( 'Location: home.php' );
exit();
}
}
?>
編輯:
針對注銷問題,使用注銷按鈕,將它們發送到 index.php?logout=true
索引.php
<?php
include('database.php');
session_start();
if ( defined( 'RESTRICTED' ) ) {
if ( !isset( $_SESSION['id'] ) ) {
header( 'Location: index.php' );
exit();
}
}
else {
if ( isset( $_GET['logout'] ) ) {
$_SESSION = array();
}
if ( isset( $_SESSION['id'] ) ) {
header( 'Location: home.php' );
exit();
}
}
?>
編輯 2
在回復評論中,一個關於如何處理登錄用戶的例子
在所有受限頁面中:
define( 'RESTRICTED', true );
require( 'header.php' );
在您希望將用戶發送到 home.php(如果他們已登錄)的所有頁面中:
define( 'SEND_TO_HOME', true );
require( 'header.php' );
頭文件.php:
<?php
if ( defined( 'RESTRICTED' ) ) {
if ( !isset( $_SESSION['id'] ) ) {
header( 'Location: index.php' );
exit();
}
}
else {
if ( isset( $_GET['logout'] ) ) {
$_SESSION = array();
}
if ( defined( 'SEND_TO_HOME' ) && isset( $_SESSION['id'] ) ) {
header( 'Location: home.php' );
exit();
}
}
?>
制作一個名為authenticate.php
的 PHP 文件
<?php
if(!isset($_SESSION['id'])) {
header('Location: index.php');
exit();
}
?>
那些需要身份驗證的文件包含在該文件中,就像在您的主頁中使用include('authenticate.php');
在你的 index.php 文件中制作一個像
<?php
<form action="process.php" method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" value="login">
</form>
?>
在process.php
執行以下操作
<?php
$username = $_POST['username'];
$password = $_POST['password'];
//make authenticate this info to your database if user is valid then redirect to home page
session_start();
$_SESSION['id'] = 1;//here id will be the retrive id from your database
header('Location: home.php');
exit();
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.