PHP: “The website has too many redirects” when use php sessions with time

蹲街弑〆低调 提交于 2019-12-13 12:17:37

问题


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.

回答1:


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.




回答2:


here is what you need to add

if(!isset($_SESSION['clientmacs'])) { 
    $_SESSION['clientmacs'] = 'something' // or it will redirect forever;
    header('Location: index.php');
}



回答3:


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.




回答4:


Try calculating the time difference outside of the IF statement.

e.g

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

if($difference > 1800){
    //Do Something
}


来源:https://stackoverflow.com/questions/11441650/php-the-website-has-too-many-redirects-when-use-php-sessions-with-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!