感谢您加入此事,我在使用服务器上的会话变量登录时遇到了麻烦,而且它在localhost上工作得很好。这是我的代码。
我的目标网页
<?php
require_once 'lock.php';
?>
My HTML code will be here....
lock.php
<?php
session_start();
require_once 'includes/connect.php';
if(empty($_SESSION['logged_in'])){
header('Location: login.php?action=not_yet_logged_in');
}
$action = $_GET['action'];
if($action=='logout'){
session_destroy();
header('Location: login.php?action=logout');
}
?>
的login.php
<?php
session_start();
require_once 'includes/connect.php';
if(isset($_SESSION['logged_in'])==true){
header('Location: index.php?action=already_logged_in');
}
?>
<?php
if (isset($_GET['action'])) {
if($_GET['action']=='not_yet_logged_in'){
echo "<div class='infoMesssage'>You cannot go to the index page because you are not yet logged in.</div>";
}else if($_GET['action']=='logout'){
echo "<div class='infoMesssage'>You have scuccessfully logout.</div>";
}
}
if($_POST){
$enUsername = $_POST['username'];
$enPassword = $_POST['password'];
if(empty($_POST['username'])){
$username = 'mockadmin';
$password = 'mockadmin';
}else {
$chLogin = mysqli_query($con, 'select * from admin where user_name="'.$enUsername.'" AND password="'.$enPassword.'"');
$chUser = mysqli_fetch_object($chLogin);
$userId = $chUser->id;
$username = $chUser->user_name;
$password = $chUser->password;
}
if($_POST['username']==$username && $_POST['password']==$password){
$_SESSION['logged_in'] = true;
header('Location: index.php');
} else{
echo "<div class='failedMessage'>Access denied. :(</div>";
}
}
?>
<form class="m-t" method="post" role="form" action="login.php">
<div class="form-group">
<input type="text" name="username" class="form-control" placeholder="Username">
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" placeholder="Password">
</div>
<button type="submit" name="btnlogin" class="btn btn-primary block full-width m-b">Login</button>
</form>
我的数据库 connect.php
<?php
$con = mysqli_connect('localhost', 'liveuser', 'livepass', 'mocktest');
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
感谢您的帮助。再次感谢。