用户通过url直接访问页面

时间:2020-09-15 00:07:30

标签: php

嗨,我想使用下面的php代码来阻止直接URL访问我的页面,但是如果我将其包含在表单中,即使输入用户名和密码后也无法登录,这就像是我的应用程序已被锁定。有人可以帮忙吗

那是我的security.php文件

<?php

if(!isset ($_SESSION['user']))
{
    header ('location:user_login.php');
}

?>

和用户登录文件

<?php


if (isset($_POST['btnLogin']))
{
    $user = $_POST['user'];
    $password = $_POST['password'];

    //sql injection security
    $user = mysqli_real_escape_string($con,$user);
    $password = mysqli_real_escape_string($con,$password);

    //select database

    $db = mysqli_select_db($con,'nesthet');

    $query = "SELECT * from users where user='$user' AND password='$password'";
    $query_run = mysqli_query($con,$query);
    $role = mysqli_fetch_array($query_run);
        
    //user redirection base on user role

    if($role['role'] == "admin"){
       
        session_start();
        $_SESSION['user'] = $user;
        header('location: admin.php');
    }
    else if($role['role'] == "user") {
        
        $_SESSION['user'] = $user;
        header('location: mdi_parent.php');
    }
    else {
        $_SESSION['status'] = "Username or password is invalid";
        header('location: index.php');
    }
}

?>

1 个答案:

答案 0 :(得分:2)

在security.php中,应在使用$ _SESSION变量之前执行session_start()

<?php
if(!isset ($_SESSION['user']))
{
    header ('location:user_login.php');
}
?>

在您的代码中,您仅在角色为admin时才开始会话

if($role['role'] == "admin"){
    session_start();
    $_SESSION['user'] = $user;
    header('location: admin.php');
}
else if($role['role'] == "user") {
    
    $_SESSION['user'] = $user;
    header('location: mdi_parent.php');
}
else {
    $_SESSION['status'] = "Username or password is invalid";
    header('location: index.php');
}