Я искал в Интернете (включая переполнение стека) ответ на происходящее, но безуспешно :( Я пытаюсь настроить пользовательский сайт, который выполняется сессиями. Мой сайт настроен вверх так:
index.php
<code><?php include("header.php");
//some html stuff
echo "<pre>";
print_r($_SESSION);
echo "
";
?>
header.php
<code><!DOCTYPE html>
<html>
<head>
<title>My title</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="style.css" />
<link rel='shortcut icon' href='images/favicon.ico' type='image/x-icon'/ >
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('America/Denver');
?>
</head>
<body>
<div class="header">
<div class='outer-nav'>
<ul>
<?php //navigation
if (isset($_SESSION['user_name'])) {
echo '<li>' . $_SESSION['user_name'] . '</li>';
} else {
echo '<li>user_name does not exist</li>';
echo "<pre>";
print_r($_SESSION);
echo "
";
}
?>
Проблема в том, что, хотя session_start();
находится в заголовочном файле, файл заголовка не будет распознавать переменные сеанса, но индексный файл, который включает в себя заголовок (и не имеет отдельного session_start();
iteself), способен чтобы получить переменные сеанса.
Я попытался переместить session_start()
вокруг и использовать ob_start
и ob_flush
, но не нашел способа получить переменные сеанса для использования в моем заголовочном файле (особенно в панели навигации). Что я делаю не так?
![what is happening](https://i.stack.imgur.com/l54Wk.png)
EDIT
Хорошо, так что я думаю, я выяснил, откуда возникла проблема. В моем индексе есть заголовок перед заголовком:
index.php
<?php include("admin/settings.php");
include("header.php");
settings.php
<?php session_start(); ?>
//just variable declarations here
header.php
//removed <?php session_start(); ?>
//see above for rest of code in header.php
Когда я изменяю код на это, теперь я получаю переменные сеанса в теле индекса, но теперь я получаю Notice: Undefined variable _SESSION in...
в заголовке. Так что теперь он даже не видит сеанс вообще ... это потому, что он включен?
Дополнительное редактирование
Информация о моей сессии от phpinfo ():
![session info](https://i.stack.imgur.com/A6CkT.png)
loggedin.php (где объявляются переменные сеанса):
<?php
include_once("admin/settings.php");
$inputusername = mysqli_real_escape_string($connect, $_POST['user_name']);
$inputpassword = mysqli_real_escape_string($connect, $_POST['user_pass']);
$sql = "SELECT user_id, user_name, user_pass, user_role, user_lastloggedin
FROM user WHERE user_name = '$inputusername'";
$result = mysqli_query($connect, $sql);
if (!$result) { //query returned a mistake
include_once($header);
echo '<div class="full_page_content">';
echo "<h1>Sign In</h1>";
echo '<center>Something went wrong while signing in. Please try again later.</center>';
//echo mysqli_error();
include_once($footer);
exit();
} elseif (mysqli_num_rows($result) == 0) { //check if user exists
include_once($header);
echo '<div class="full_page_content">';
echo "<h1>Sign In</h1>";
echo '<center>That username does not exist. Please check your spelling and try again.</center>';
include_once($footer);
exit();
} else { //user was found, continue login
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['user_name'];
$pass = $row['user_pass'];
$id = $row['user_id'];
$role = $row['user_role'];
$last = $row['user_lastloggedin'];
}
$errors = array();
if (empty($inputpassword)) { //check if password field is empty
$errors[] = '<center>The password field must not be empty</center>';
} elseif (!password_verify($inputpassword, $pass)) {
$errors[] = '<center>The password you entered was incorrect. Please check your spelling and try again.</center>';
}
if (!empty($errors)) { //if there are errors...
include_once($header);
echo '<div class="full_page_content">';
echo "<h1>Sign In</h1>";
echo '<ul>';
foreach ($errors as $key => $value) {
echo '<li>' . $value . '</li>';
}
echo '</ul>';
include_once($footer);
exit();
} else {
//there are no errors, process the form
$_SESSION['signed_in'] = true;
$_SESSION['user_id'] = $id;
$_SESSION['user_name'] = $name;
$_SESSION['user_role'] = $role;
$now = time();
if (strlen($last) == 1) {
$_SESSION['first'] = true;
header("Location: changepass.php");
} else {
mysqli_query($connect, "UPDATE users SET user_lastloggedin='$now' WHERE user_id = '$id'");
header("Location: index.php");
}
}
}
?>