【问题标题】:PHP: "The website has too many redirects" when use php sessions with timePHP:随着时间的推移使用 php 会话时,“网站的重定向太多”
【发布时间】:2012-07-11 14:27:03
【问题描述】:

在我的页面中使用此代码时遇到问题:

带有过期会话的代码

<?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
}
?>

但如果我使用此代码,问题就会消失,页面可以正常工作:

没有过期会话的代码

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

谷歌浏览器出错:

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.

【问题讨论】:

    标签: php session timeout


    【解决方案1】:

    执行重定向时需要重新设置超时的$_SESSION值($_SESSION['timeLogin']),否则当客户端从重定向返回时,会话中的值相同,将再次重定向。

    你可以解决它:

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

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

    也许(取决于您的逻辑)最好清除整个会话,并在您执行重定向时通过正常流程 (session_destroy()) 重新配置它。

    【讨论】:

    • 对我有用,@Ibu 也可以回答!
    【解决方案2】:

    尝试在 IF 语句之外计算时间差。

    例如

    $difference = time() - $_SESSION['timeLogin'];
    
    if($difference > 1800){
        //Do Something
    }
    

    【讨论】:

      【解决方案3】:

      您的注销正在重定向到您的索引,它将再次检查条件

      if(time() - $_SESSION['timeLogin'] &gt; 1800)

      这将是真实的并将其发送回注销,依此类推。你需要改变你的 $_SESSION['timeLogin'] 否则你永远不会打破这个循环。

      【讨论】:

        【解决方案4】:

        这是您需要添加的内容

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

        【讨论】:

        • 其他php文件中添加的会话名!
        • @SoldierCorp 您必须仔细检查,因为这就是导致您无限重定向的原因
        • 对我和@Francisco Spaeth 也有用! ://
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-24
        • 2014-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-10
        相关资源
        最近更新 更多