PHP: “The website has too many redirects” when use

2019-04-14 22:43发布

I've a problem when use this code in my page:

Code with expire session

<?php 
session_start();
if(!isset($_SESSION['clientmacs']) ) { 
    header('Location: index.php');
} else {
    if(time() - $_SESSION['timeLogin'] > 1800) {
        header('Location: include/logout.php');
    }
    $userclient = $_SESSION['clientmacs'];
?>
<html>
    HTML CODE
</html>
<?php
}
?>

But if I use this code the problem disappears and the page works normally:

Code without expire session

<?php 
session_start();
if(!isset($_SESSION['clientmacs'])) { 
    header('Location: index.php');
} else {
    $userclient = $_SESSION['client'];;
?>
<html>
    HTML CODE
</html>
<?php
}
?>

Error in Google Chrome:

This webpage has a redirect loop

Http://localhost/mac/index.php The website has too many redirects. The incidence may be
resolved by deleting the cookies from this site or allowing third party cookies. If
that fails, the incidence may be related to a bug in the server configuration, not the
computer.

4条回答
SAY GOODBYE
2楼-- · 2019-04-14 23:10

here is what you need to add

if(!isset($_SESSION['clientmacs'])) { 
    $_SESSION['clientmacs'] = 'something' // or it will redirect forever;
    header('Location: index.php');
}
查看更多
够拽才男人
3楼-- · 2019-04-14 23:19

Your logout is redirecting to your index, where it will check the condition again

if(time() - $_SESSION['timeLogin'] > 1800)

Which will be true and will send it back to logout, and so on and so forth. You need to change yoiur $_SESSION['timeLogin'] or you will never break this cycle.

查看更多
Deceive 欺骗
4楼-- · 2019-04-14 23:28

Try calculating the time difference outside of the IF statement.

e.g

$difference = time() - $_SESSION['timeLogin'];

if($difference > 1800){
    //Do Something
}
查看更多
家丑人穷心不美
5楼-- · 2019-04-14 23:29

You need to reset the $_SESSION value for timeout ($_SESSION['timeLogin']) when you execute redirection, otherwise when the client is back from redirect the value in session is the same and will be again redirected.

You could solve it with:

if(!isset($_SESSION['clientmacs']) ) {
    $_SESSION['clientmacs'] = ""; // add this line if not added somewhere else
    header('Location: index.php');
}

and

if(time() - $_SESSION['timeLogin'] > 1800) {
    $_SESSION['timeLogin'] = time(); // add this line
    header('Location: include/logout.php');
}

Maybe (depending on your logic) is better clear the entire session, and let it be reconfigured through the normal flow (session_destroy()) when you perform redirect.

查看更多
登录 后发表回答