im试图编写一个函数,当用户试图访问索引(主页)页面时,该函数会将用户重定向到其配置文件页面。我已经能够使用POST数据从登录表单成功地做到这一点,但在以这种方式提取会话数据时遇到了问题。Firefox表示,服务器正在以一种永远不会完成的方式重定向。
这就是我所尝试的,正如在我的一般功能中所写的:
function logged_in_redirect() {
if (logged_in() === true) {
header('Location: '.$_SESSION['username'].'');
//header('Location: '.$user_data['username'].''); *NEITHER LINE WORKS
exit();
}
}
以及我添加重定向的索引页面:
<?php
include 'core/init.php';
logged_in_redirect();
include 'includes/overall/header.php';
?>
<h1>Home</h1>
<p>Just a template.</p>
<?php include 'includes/overall/footer.php'; ?>
我的init包括:
<?php
ob_start();
session_start();
//error_reporting(0);
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
if (logged_in() === true) {
$session_user_id = $_SESSION['user_id'];
$user_data = user_data($db, $session_user_id, 'user_id', 'username', 'password', 'first_name', 'last_name', 'email', 'stack_code');
if (user_active($db, $user_data['username']) === false) {
session_destroy();
header('Location: index.php');
exit();
}
}
$errors = array();
?>
iv修改了我的.htaccess和其他关于配置文件url的一切都很好。只是这个重定向今天把我逼疯了。谢谢
好简单,我只需要通过重定向函数在init中传递$user_data变量,而且当我调用函数时:
function logged_in_redirect($user_data) {
if (logged_in() === true) {
header('Location: '.$user_data['username'].'');
exit();
}
}
您必须检查访问的页面是否是将用户移动到配置文件页面的索引页面。像这样:
$page = isset($_POST['page']) ? clear_get_tag($_POST['page']) : NULL;
$session_user_id = $_SESSION['user_id'];
$user_data = user_data($db, $session_user_id, 'user_id', 'username', 'password', 'first_name', 'last_name', 'email', 'stack_code');
switch($page){
case 'index':
case NULL:
if (logged_in() === true && !is_null($user_data) ) {
//call the redirect function here if the user is logged
}else{
// echo the index page
}
break;
case 'user':
echo 'user profile';
break;
default:
// Check if something else was called rather than defined pages, and returns the page depend on if the user is logged in.
if (logged_in() === true) {
header('Location: '.$user_data['username'].'');
}else{
header('Location: index.php');
}
break;
}