PHP 限制文件访问的会话
PHP Session to restrict access to file
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>";
}
}
display.php
session_start();
if(!$_SESSION['loggedIn']) {
header("location: index.php");
die();
}
你好,我想弄清楚为什么我的 index.php 不允许我正确登录和访问我的 display.php 密码和用户名是正确的,但一直将我重定向到 index.php 有什么想法吗?
为什么不改用 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();
}
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>";
}
}
display.php
session_start();
if(!$_SESSION['loggedIn']) {
header("location: index.php");
die();
}
你好,我想弄清楚为什么我的 index.php 不允许我正确登录和访问我的 display.php 密码和用户名是正确的,但一直将我重定向到 index.php 有什么想法吗?
为什么不改用 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();
}