我正在一个有登录表单的网站上工作。用户可以输入信息,如果错误,则站点发送警报。但是,问题是您可以在登录后通过更改地址栏中的名称轻松访问该页面。
这很糟糕,因为您无需登录即可轻松进入页面。
validation.php:
<?php
$name =$_POST['user'];
$pass =$_POST['password'];
//Test code
//echo $pass;
//End Test Code
//Connection Code
session_start();
$con = mysqli_connect('localhost', 'root', '');
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
mysqli_select_db($con, 'userregistration');
// Connection End
//Query Code
$s = "select * from usertable where name = '$name' and password = '$pass'";
//test
//echo $s;
$result = mysqli_query($con, $s);
$num = mysqli_num_rows($result);
if($num == 1){
echo "Hello " . $name;
}
else{
echo "<script>";
echo "alert('Incorrect Username or Password');";
echo "window.location.replace('login.html');";
echo "</script>";
}
?>
<!--html code-->
Donate.php
<center><h1>Donate Here!</h1></center>
您必须在成功登录后创建会话:
session_start();
if ($num == 1) {
$_SESSION['username'] = $name;
}
现在在Donate.php中通过检查会话是否已设置来检查用户是否已登录:
session_start();
if (!isset($_SESSION['username']) || empty($_SESSION['username'])) {
// no session, redirect user to index.php
header('location: index.php');
}
如果你想限制Donate.php试试这个
<?php
session_start();
if (empty($_SESSION['user_id'])) {
header('Location:login.php');
} ?>
<center><h1>Donate Here!</h1></center>
您必须在会话中设置某种标记,以标记您的用户已通过身份验证(已登录)。您可以在$_SESSION['current_user_id']
中存储当前用户的user_id。
还请注意你的查询是sql注入的好目标,所以不要忘记SQL转义你通过mysqli_real_escape_string
添加到sql查询的任何数据
validation.php:
//...
$s = "select * from usertable where name = '"
.mysqli_real_escape_string($con, $name).
"' and password = '"
.mysqli_real_escape_string($con, $pass)
."'";
$result = mysqli_query($con, $s);
if ($row = mysqli_fetch_row($result))
{
// row fecthed, user found
$user_id = $row['user_id']; // Let expect that usertable has user_id column
$_SESSION['current_user_id'] = $user_id;
}
else
{
echo "<script>";
echo "alert('Incorrect Username or Password');";
echo "window.location.replace('login.html');";
echo "</script>";
exit();
}
//...
在你的所有页面上,在最开始的时候放下代码:
some_page.php:
if (!isset($_SESSION['current_user_id'])) { exit('Your session expiried!') }
//... do some stuff
要注销您的用户,您可以取消设置$_SESSION['current_user_id']
logout.php:
unset($_SESSION['current_user_id']);