错误:不允许我通过会话输入我的PHP信息中心

时间:2019-01-06 19:15:15

标签: php mysql

我正在为学校做一项活动,尝试登录时,我必须重定向到“ dashboard.php”,但它不会重定向我,并且当我尝试输入指向仪表板的URL时,它会将我重定向到“索引” (这是我在没有会话时插入的页面),如果有会话,则应转到“仪表板”

登录功能

function login($username, $password)
{
    global $mysqli;

    $stmt = $mysqli->prepare("SELECT id, password FROM users WHERE username = ? || email = ? LIMIT 1");
    $stmt->bind_param("ss", $username, $username);
    $stmt->execute();
    $stmt->store_result();
    $rows = $stmt->num_rows;

    if($rows > 0) {

        if(isActivo($username)){

            $stmt->bind_result($id, $passwd);
            $stmt->fetch();

            $validaPassw = password_verify($password, $passwd);

            if($validaPassw){

                lastSession($id);
                $_SESSION['id_user'] = $id;

                header("Location: dashboard.php");
            } else {

                $errors = "La contraseña es incorrecta";
            }
        } else {
            $errors = 'El usuario no esta activo';
        }
    } else {
        $errors = "El nombre de usuario o correo electrónico no existe";
    }
    return $errors;
}

login.php

require './config/conexion.php'; //here is the db connection file
require './config/funcs.php'; // here is the login function and another functions

session_start();

if(isset($_SESSION['id_user'])) {
  header("Location: dashboard.php");
}

$errors = array();

if(!empty($_POST)) {
  $username = $mysqli->real_escape_string($_POST['username']);
  $password = $mysqli->real_escape_string($_POST['password']);

  if(isNullLogin($username, $password)){
    $errors[] = "Debe llenar todos los campos";
  }
  $errors[] = login($username, $password);
}

dashboard.php

session_start();
require './config/conexion.php';
include './config/funcs.php';

if(!isset($_POST['id_user'])) {
    header('Location: index.php');
} 

$idUser = $_SESSION['id_user'];

$sql = "SELECT id, username FROM users WHERE id = '$idUser'";
$result = $mysqli->query($sql);

$row = $result->fetch_assoc();

和我的index.php

require './config/conexion.php';
require './config/funcs.php';

session_start();

if(isset($_SESSION['id_user'])) {
  header("Location: dashboard.php");
}

然后,当我登录时,我应该转到“仪表板”,但是它将重定向到“索引”,并且我不知道如何查找该解决方案,我已经进行了一些调查,但是我想这是一个错误。代码或类似的东西。 我是php的新手。

谢谢

1 个答案:

答案 0 :(得分:1)

首先,在设置任何会话之前,您还需要使用 session_start()! 其次,在登录功能中,设置 session ,但是在仪表板中检查 POST ,则应替换:

if(!isset($_POST['id_user'])) {
 header('Location: index.php');
}

使用:

if (!isset($_SESSION['id_user'])) {
    exit(header('Location: index.php'));
}