【问题标题】:PHP Session to restrict access to filePHP Session 限制对文件的访问
【发布时间】:2015-08-16 06:20:42
【问题描述】:

index.php

session_start();

if(isset($_POST['login'])){

$username = mysqli_real_escape_string($con,$_POST['username']);

$pass = mysqli_real_escape_string($con,$_POST['userpass']);

$sel_user = "select * from users where user_name='$username' AND user_password='$pass'";

$run_user = mysqli_query($con, $sel_user);

$check_user = mysqli_num_rows($run_user);

if($check_user>0) {

$_SESSION['loggedIn'] = true;
$_SESSION['user_name']=$username;

header("location:display.php");
die();
}

else {

echo "<script>alert('Username or Password is not correct, please try again!')</script>";

}

}

显示.php

session_start();

if(!$_SESSION['loggedIn']) {
header("location: index.php");
die();
}

您好,我想弄清楚为什么我的 index.php 不能让我正确登录和访问我的 display.php 密码和用户名是正确的,但不断将我重定向到 index.php 有什么想法吗?

【问题讨论】:

  • 那么它现在重定向到哪里了?
  • 我相信我在 index.php 中的代码在某种程度上是错误的。即使登录凭据正确,我也不需要 display.php
  • 您是否将密码明文存储到数据库中? o_O
  • 是的,我没有包含 php 代码的 mysqli 连接部分
  • 我不想成为那些人中的一员,但永远不要以明文形式存储密码,除非你现在解决这个问题,否则你将来会吸取教训:)

标签: php session session-variables


【解决方案1】:

为什么不使用 Cookie 来代替? 在您的 login.php 页面中,而不是:

if($check_user>0) {

$_SESSION['loggedIn'] = true;
$_SESSION['user_name']=$username;

header("location:display.php");
die();
}

这样做:

if($check_user>0) {
    $_SESSION['user_name']=$username;
     $Month = 86400 + time(); 
     setcookie('user', $username, $Month); 
      header("Location:display.php");
}

然后在你的display.php

session_start();

if(!isset($_COOKIE['user']))
{
header("location:index.php");
die();
}

【讨论】:

  • 用户不能在他的浏览器上禁用cookies吗?
  • @ArvinFlores 是的,但这是故事的另一面。您还可以更改浏览器中的会话到期/重置设置。
  • 感谢您的帮助。我对 php 相当陌生,所以我什至不知道这可以通过 cookie 实现。我只是好奇你是怎么推荐饼干的?会话在某种程度上是劣质的吗?
  • @ArvinFlores cookie 存储在客户端,而会话则存储在服务器上。更深入的研究请看这里:php.about.com/od/learnphp/qt/session_cookie.htm
  • 那篇文章确实澄清了一些事情。非常感谢。要求查看会话中使用的上述代码是否太过分了?供我以后参考
猜你喜欢
  • 2023-03-05
  • 2013-01-04
  • 1970-01-01
  • 2012-04-03
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多