几乎让我的登录脚本工作,但会话变量出现了一个奇怪的问题。我创建了运行
中的登录代码的会话变量./包括/ functions.php的
由于某种原因,它们不存在于同一页面上,因为我的check_login函数也在functions.php页面上。但是当我做检查时它失败了:
function login_check($mysqli) {
//Check if session variables are met
if (isset($_SESSION['user_id'], $_SESSION['email'], $_SESSION['login_string'])) {
我有另一个名为process_login.php的页面,该页面位于
中./ PHP / process_login.php
会话变量在这里工作,因为我从以下代码中获取了正确的信息
<?php
include "../includes/db_connect.php";
include "../includes/functions.php";
include "../includes/required.php";
if(isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = hash('sha512', $_POST['p']); //Encrypted password
if (login($email, $password, $mysqli) == true) {
//Login success
echo "Logged in!";
//header("Location: ".ROOT."index.php");;
} else {
//Not user found
echo "Not user found with those details";
}
}
?>
<h1>You are logged in as <?=$_SESSION['email']?>!</h1>
<h2>Your user ID is: <?=$_SESSION['user_id']?>.</h2>
<h2>You have <?=$_SESSION['perms']?> rights.</h2>
这是我的登录脚本,它创建了会话变量
function login($email, $password, $mysqli) {
//Use prepared statements to stop SQL Injection
if ($stmt = $mysqli->prepare("SELECT id, email, password, salt, perms FROM users WHERE email = ? LIMIT 1")) {
$stmt->bind_param('s', $email); //Bind "$email" to paramater
$stmt->execute(); //Execute the query
$stmt->store_result();
$stmt->bind_result($user_id, $email, $db_password, $salt, $perms); //get variables from result
$stmt->fetch();
$password = hash('sha512', $password.$salt); //hash the password with the unique salt
if ($stmt->num_rows == 1) { //If user exists
//Check that user account isn't locked
if (checkbrute($user_id, $mysqli) == true) {
//Account is locked, alert user
return false;
} else {
if ($db_password == $password) { //Check that passwords match
//matches, create session
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = $email;
$user_browser = $_SERVER['HTTP_USER_AGENT']; //Create hash with password and user agent
$_SESSION['login_string'] = hash('sha512',$password.$user_browser);
$_SESSION['perms'] = $perms;
return true;
}
}
} else {
return false;
}
} else {
//Error
echo "Prepare failed: (".$mysqli->errno.") ".$mysqli->error;
}
}
这可能是我的会话脚本的问题,如下所示。是否需要此脚本,或者我可以简单地使用
在session_start();
我正在使用该脚本使其更安全一些。
function sec_session_start() {
$session_name = 'ppa_session_id'; //Custom session name
$secure = false; //Set to true if using https
$httponly = true; //Stops JavaScript being able to access session id
ini_set('session.use_only_cookies', 1); //Force current cookie params
$cookieParams = session_get_cookie_params(); //Gets current cookie params
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
session_name($session_name); //Sets the session name to the custom one
session_start(); //Start the session
session_regenerate_id(); //regenerate the session, delete the old one
}
答案 0 :(得分:6)
每个包含$ _SESSION ['']的页面都需要有session_start();在打开php之后的页面顶部