[英]Redirect to login page if user is not logged in - PHP
I am working on a PHP task.我正在处理 PHP 任务。 I have two pages.我有两页。 On e is for login and after successfully login, user will redirect to next page. e 用于登录,登录成功后,用户将重定向到下一页。 But if someone enters URL of page2 in URL bar without going to page to through login page.但是如果有人在 URL 栏中输入 page2 的 URL 而没有通过登录页面跳转到页面。 They can, I want to restrict this.他们可以,我想限制这个。 But have no idea, how... here's my code of login page.但不知道,如何......这是我的登录页面代码。
<html>
<body>
<div id="content">
<h3>Login to AdminUpdate</h3>
<form id="login" action="" method="post">
<p>
<label for="userid">UserID:</label>
<input type="text" name="Name" id="UserID"/>
</p>
<p>
<label for="PIN">PIN:</label>
<input type="password" name="password" id="PIN" />
</p>
<p>
<input type="submit" name="btnSend" value="Login" class="submit_button" />
</p>
</form>
<td> </td>
<div id="wrap">
<!-- start PHP code -->
<?php
$conn = mysqli_connect("localhost", "root", "", "tnz");
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
if(!empty($_POST['Name']) && (!empty($_POST['password']))){
$UserName = $_POST['Name'];
$PIN = $_POST['password'];
$search = mysqli_query($conn,"SELECT * FROM login WHERE Name='".$UserName."' AND password='".$PIN."'") or die(mysql_error());
$match = mysqli_num_rows($search);
if($match > 0){
header('Location: AdminUpdates.php');
}else{
echo 'LogIn Failed';
header('Location: AdminCheck.php');
}
}
?>
</div>
</div>
</body>
</html>
Start by reading more about this topic: Sessions首先阅读有关此主题的更多信息:会话
This little sample of code may help as well.这个小代码示例也可能有所帮助。
On the login page try this:在登录页面上试试这个:
<?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "tnz");
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
if(!empty($_POST['Name']) && (!empty($_POST['password']))){
$UserName = $_POST['Name'];
$PIN = $_POST['password'];
$search = mysqli_query($conn,"SELECT * FROM login WHERE Name='".$UserName."' AND password='".$PIN."'") or die(mysql_error());
$match = mysqli_num_rows($search);
if($match > 0){
$_SESSION['loggedin'] = true;
header('Location: AdminUpdates.php');
}
else{
echo 'LogIn Failed';
header('Location: AdminCheck.php');
}
}
?>
Then, on the page two add the following code at the top of the script:然后,在第二页的脚本顶部添加以下代码:
<?php
session_start();
if(empty($_SESSION['loggedin'])){
//redirect to login page
header('Location: AdminCheck.php');
die;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.