【问题标题】:header('location:index.php') doesn't work in the first runheader('location:index.php') 在第一次运行时不起作用
【发布时间】:2013-02-09 20:41:00
【问题描述】:

我有一个 index.php 页面,里面设置了一个会话($_SESSION['expire'])。此会话应在 30 分钟后取消设置,我们应重定向到 index.php(再次验证用户)。

我的 index.php 代码的一部分:

<?php
session_start();
//if user name and password are valid do the following:
$_SESSION['start'] = time(); 
$_SESSION['expire'] = $_SESSION['start'] + (30 * 60) ;
?>

<a href="index.php?action=ContentManager">
    content 
</a>

<?php    
if(isset($_REQUEST['action']))

{
    //if the expiration time has not reached yet do the following
    $now=time();
    if (isset($_SESSION['expire']) && ($now<= $_SESSION['expire'])) 
    {
        switch($_REQUEST['action'])
        {
            case 'ContentManager' : 
              include('model/content.php');
              $contents = getContent($conn, ' where 1=1');
              include('view/contentmanager.php');
              break;
        }
    }

    else if($now > $_SESSION['expire'])
    {
        unset($_SESSION['expire']);
        session_destroy();
        header('location:index.php');
       exit();
    }   
}
?>

问题是,当我在 30 分钟后单击 contentmanager 链接时,我们将重定向到带有 url 的空页面: index.php?action=contentmanager

只有当我再次刷新页面时,我们才会重定向到 index.php 本身并出现登录表单。

简而言之:我必须刷新页面两次才能重定向到正确的页面。

提前致谢

【问题讨论】:

  • 在处理完请求和所有数据之前不要输出任何东西。这也将帮助您避免意大利面条式代码。

标签: php session header location href


【解决方案1】:

使用ob_start();

<?php
session_start();
ob_start();
//if user name and password are valid do the following:
$_SESSION['start'] = time(); 
$_SESSION['expire'] = $_SESSION['start'] + (30 * 60) ;
?>

<a href="index.php?action=ContentManager">
    content 
</a>

<?php    
if(isset($_REQUEST['action']))

{
    //if the expiration time has not reached yet do the following
    $now=time();
    if (isset($_SESSION['expire']) && ($now<= $_SESSION['expire'])) 
    {
        switch($_REQUEST['action'])
        {
            case 'ContentManager' : 
              include('model/content.php');
              $contents = getContent($conn, ' where 1=1');
              include('view/contentmanager.php');
              break;
        }
    }

    else if($now > $_SESSION['expire'])
    {
        unset($_SESSION['expire']);
        session_destroy();
        header('location:index.php');
       exit();
    }   
}
ob_end_flush();
?>

【讨论】:

  • 最好删除 ob_start() 并在开始时检查过期,然后再发送任何内容到输出,在这种情况下,在&lt;a href="index.php?action=ContentManager"&gt; content &lt;/a&gt;之前
猜你喜欢
  • 2012-12-28
  • 1970-01-01
  • 1970-01-01
  • 2021-05-20
  • 1970-01-01
  • 1970-01-01
  • 2023-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多