gpt4 book ai didi

php - 警告 : Cannot modify header information - headers already sent (PHP)

转载 作者:可可西里 更新时间:2023-11-01 13:51:35 27 4
gpt4 key购买 nike

<分区>

我的问题有点类似于下面的帖子..

PHP error: Cannot modify header information – headers already sent

但在我的例子中,我选择在确定登录表单没有验证错误并且用户的登录信息与数据库的登录信息匹配后启动 session 。下面是代码:

登录页面(在任何 html 之前)

session_name('username');
session_name('ip');
session_name('start');
session_start();

Login.php 片段(在 html 正文中)

         } else {
$user = $_POST['username'];
$userpass = md5($_POST['password']);
$login_results = statement("select username, password from `$admin` where username='$user' and password='$userpass'");

if (mysql_num_rows($login_results)!= 1) {
$errmsg = "<span id='error'>Login failed: Username or password not on file</span>";
}else {

$_SESSION['username'] = "$user";
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
header("Location: index.php");
}
}
}

}

如果您查看上面代码的 else block ,我正在验证登录,如果它正常,我想分配 session 变量并转到我的索引页面。开头有这段代码:

 //Session Timeout Script -- used to determine the amount of time the user has been idle.  If it the user has been idle for longer then the session time, log the user out.
//Secondary to the Timeout Script, the username and ip address is checked for validility and if either fails redirect the user to the login page.
session_cache_expire( 20 );
session_start();

$inactive = 1200;

if(isset($_SESSION['start']) ) {
$session_life = time() - $_SESSION['start'];
if($session_life > $inactive){
header("Location: logout.php");
}
}

$_SESSION['start'] = time();

$newip = $_SERVER['REMOTE_ADDR'];
if (!isset($_SESSION['username']) || empty($_SESSION['username']) || $newip!= $_SESSION['ip']) {
header('Location: login.php');
}

现在阅读前一位作者的问题,有人提到 header() 应该是发送重定向的代码中执行的第一件事,在我的例子中是 login.php。这样做允许我登录,但是当我注销时,我正在销毁我的所有 session 并使用 header() 将我发送回登录页面。这将使登录页面重定向回索引页面,因为它读取了第一行代码。有没有办法避免这种情况?这样我就不需要重复我已经在 login.php 顶部设置的一些代码逻辑了吗?

安德烈

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com