【发布时间】:2018-04-16 22:36:53
【问题描述】:
我有 2 页。我需要在“addproduct.php”上检查用户是否以管理员身份登录。我有一个登录脚本。抱歉,如果这是一个愚蠢的问题,但我对 PHP 来说是全新的。
我希望访问此页面但未以管理员身份登录的用户(“isadmin”是用户数据库中的一行)重定向到登录页面,并且当有人以管理员身份登录时要显示的页面。
登录.php;
<?php
session_start();
$un = $_POST["username"];
$pw = $_POST["password"];
$conn = new PDO ("mysql:host=localhost;dbname=assign026;", "assign026",
"ziSietiu");
$results = $conn->query("select * from users where username='$un' and
password='$pw'");
$row = $results->fetch();
if($row == false)
{
echo "Incorrect password!";// There were matching rows
}
else
{
$_SESSION["gatekeeper"] = $un;
$_SESSION["isadmin"] = $row["isadmin"];
header ("Location: index.php");
}
?>
然后添加product.php
<?php
session_start();
?>
<?php
// Test that the authentication session variable exists
if(!isset($_SESSION["isadmin"]) || $row["isadmin"] == 1)
{
header('Location: login.html');
exit();
}
else
{
echo ($_SESSION["isadmin"]);
}
?>
<div>
<h2>Add new product</h2>
<form method="post" action="addproductscript.php">
<p>Insert product here</p>
<input type="text" name="name" placeholder="name">
<input type="text" name="manufacturer" placeholder="manufacturer">
<input type="text" name="description" placeholder="description">
<input type="text" name="price" placeholder="price">
<input type="text" name="stocklevel" placeholder="stocklevel">
<input type="text" name="agelimit" placeholder="agelimit">
<input type="submit" value="Submit">
</form>
</div>
【问题讨论】:
-
那行
if(!isset($_SESSION["isadmin"]) || $row["isadmin"] == 1)会抛出一个错误,因为$row没有定义。所以脚本停在那里。 -
有一个文件,您在用户需要登录的任何地方都包含该文件(作为管理员?)该文件进行检查和重定向。在该文件中,您可以首先检查 `$_SESSION['isadmin']' 是否存在,如果不存在,请检查给定的 authToken 是否与数据库匹配..
-
行在第一个(登录)脚本中定义
-
那些脚本没有连接(还没有?不是我可以在这里看到的)。因此,除非您删除了某些代码
$row未在addProduct.php中定义 -
"uni work", "theres no risk of user data" - 所以你正在学习。那你为什么不马上学呢??