简体   繁体   English

将用户重定向到登录页面

[英]redirect users to the login page

I've got the following login script.. 我有以下登录脚本。

<?php
$name = $_POST["name"];
$password = $_POST["password"];
$query = "SELECT * FROM users WHERE username = '$name'
         AND password = '$password'";
$q=mysql_query($query) or die(mysql_error());
$result = mysql_query($query);
if (mysql_fetch_row($result)) {
  /* access granted */
  session_start();
  header("Cache-control: private");
  $_SESSION["access"] = "granted";
  header("Location: ./menu.php");
  } else
  /* access denied &#8211; redirect back to login */
  header("Location: ./login.html");
  ?>
  mysql_close();
  ?>

But what would I now need to "menu" to redirect users who are not logged in to the login page? 但是,现在我需要“菜单”将未登录的用户重定向到登录页面吗? to prevent direct access? 防止直接访问?

Thanks. 谢谢。

in menu.php? 在menu.php中?

session_start();
if (!isset($_SESSION['access']) || $_SESSION['access'] != "granted") {
  header("Location: ./login.html");
  exit();
}

You have to put something like this at the top of menu.php: 您必须在menu.php的顶部放置以下内容:

<?php
    session_start();
    if(!isset($_SESSION['access']) || $_SESSION['access'] != 'granted'){
        header("Location: ./login.html');
    }
?>

And don't forget to sanitize your query input: 并且不要忘记清理您的查询输入:

$name = mysql_real_escape_string(stripslashes($_POST["name"]));    
$password = mysql_real_escape_string(stripslashes($_POST["password"]));    

And don't forget to call session_start(); 并且不要忘了调用session_start(); at the beginning of each script that uses $_SESSION 在每个使用$_SESSION脚本的开头

Check the value of $_SESSION["access"] on the top of your menu.php. 检查menu.php顶部$_SESSION["access"]的值。 Also, you miss a call to session_start . 另外,您错过了对session_start的呼叫。 It may not be needed if you have session.auto_start enabled, but it's good habit to explicitly call it. 如果启用了session.auto_start,则可能不需要它,但是显式调用它是一个好习惯。

检查菜单中的$_SESSION["access"]以查看用户是否已登录。顺便说一句,您应该阅读SQL注入并使用转义重写该SQL查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM