简体   繁体   中英

Redirection loop issue with PHP code

I'm new to the forums here, so apologies if i'm forgetting to include information that could be helpful.

I've successfully built a login page for my test website, and have been trying to implement redirection functionality that will redirect the user to the homepage if their session already exists.

Here is my code:

<?php


if (empty($_SESSION['username'])) {
        header('Location: home');
        die();
}else{
        header('Location: index.php');
        die();
}
?>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Login</title>
</head>

<body>
<!--HTML form stuff goes here-->

I'm using Chrome, but always get the "This webpage has a redirect loop" message whenever I reload. I'm sure it has something to do with the else{} statement, as it works perfectly fine when it's excluded and when a session DOES exist.

Some help would be much appreciated.

That file can never be viewed in the browser, as it will always redirect to either home or index.php . If the code you have pasted is from either home or index.php it's a redirect loop. And if that's the case there's no reason to redirect as you're already at that page.

ideally you must have given data of all files

i am making an assumption that all your files have same code segment as you specified above for login session verification

then i can say possibly this is happening your login page redirects to index.php which again does same checking and again redirects to itself which is index.php and so on ... and your browser gets stuck in redirect loop.

for solving this problem you can do this your login.php code checks for both cases if user is logged in or not and redirects suitably

login.php

if (empty($_SESSION['username'])) {
// not logged in redirect
        header('Location: home');
        die();
}else{
//logged in redirect
        header('Location: index.php');
        die();
}

and in index.php check only if user is not logged in , if he isn't then send back to login.php else stay here

index.php

if (empty($_SESSION['username'])) {
// not logged in redirect
        header('Location: login.php');
        die();
}else{
//logged in 
//do nothing
}

similarly you can check if already logged in ,in home/index.php file and do suitably . Though my suggested solution isn't as efficient as it can be , I hope it gives you the central idea as to why you are in redirect loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM