我正在做这个教程How to create a login system in PHP
我正在尝试使用IF语句检查是否设置会话ID。当前允许用户登录并回显当前会话ID。当我故意输入错误的密码时,代码应该回显消息,但它不会做任何事情。另外,我无法使用注销按钮来终止会话。
这是我的登录页面
<?php
session_start();
//include 'dbh.php';
//probably do not need this can write connection in this file too
$conn = new PDO('mysql:host=localhost;dbname=testtable', 'root', '');
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
if(!$conn){
die("Connection is fubar yo!!! ");
}
$uid = $_REQUEST['uid'];
$pwd = $_REQUEST['pwd'];
$sql = "SELECT * from user WHERE uid='$uid' AND pwd='$pwd'";
$result = $conn->prepare($sql);
$result->execute();
if(!$row = $result->fetch(PDO::FETCH_ASSOC)){
echo("Your username or Password is wrong");
} else {
echo("hey man..it works");
$_SESSION['id'] = $row['id'];
}
header("Location: fakelogin.php");
?>
这是我的退出页面。
<?php
session_start();
session_destroy();
header("Location: fakelogin.php");
?>
这是包含登录,注册和注销按钮的主页面。
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Look ma, no hands!</title>
</head>
<body>
<form action="login.php" method="POST">
<input type="text" name="uid" placeholder="Enter username"><br>
<input type="password" name="pwd" placeholder="Enter password"><br>
<button type="submit" id="login">LOGIN</button>
</form>
<?php
echo("testing");
if(isset($_SESSION['id'])){
echo($_SESSION['id']);
} else {
echo("You are not logged in");
}
?>
<br><br><br>
<form action="signup.php" method="POST">
<input type="text" name="first" placeholder="Enter first name"><br>
<input type="text" name="last" placeholder="Enter last name"><br>
<input type="text" name="uid" placeholder="Enter username"><br>
<input type="password" name="pwd" placeholder="Enter password"><br>
<button type="submit" id="sbt">SIGN UP HERE YO!</button>
</form>
<br><br><br>
<form>
<button action="logout.php">LOG OUT</button>
</form>
</body>
</html>
答案 0 :(得分:0)
根据您提供的代码,您将始终返回登录页面。
登录后,登录按钮下方的字符串会显示测试,然后是您的用户帐户ID。
否则,它会显示测试你没有登录。
您无法在login.php
上添加消息,并希望它自动显示在fakelogin.php
上。
有很多方法可以在页面之间共享信息,会话变量就是其中之一。
通过使用以下方法,您可以将会话变量id
设置为“您的用户名或密码错误”,并且如果有值,fakelogin.php
将打印出来,这应该显示错误消息。
<强>的login.php 强>
<?php
session_start();
//include 'dbh.php';
//probably do not need this can write connection in this file too
$conn = new PDO('mysql:host=localhost;dbname=testtable', 'root', '');
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
if(!$conn){
die("Connection is fubar yo!!! ");
}
$uid = $_REQUEST['uid'];
$pwd = $_REQUEST['pwd'];
$sql = "SELECT * from user WHERE uid='$uid' AND pwd='$pwd'";
$result = $conn->prepare($sql);
$result->execute();
if(!$row = $result->fetch(PDO::FETCH_ASSOC)){
echo("Your username or Password is wrong");
$_SESSION['id'] = "Your username or Password is wrong";
} else {
echo("hey man..it works");
$_SESSION['id'] = $row['id'];
}
header("Location: fakelogin.php");
?>
因此,当您尝试使用错误的详细信息登录时,您会看到测试您的用户名或密码错误。
对于退出按钮的问题,您的HTML存在问题。 action
属性应该在form
标记中,而不是button
标记。
<form action="logout.php">
<button>LOG OUT</button>
</form>