I am facing a problem while testing simple basic php site that is if user is already logged on then header should move to home.php whenever he tries to visit login page. how to set up this?The code used is: For login.php:
<body>
<center>
<font color=red>
<?php
if(isset($_GET['msg']))
echo $_GET['msg'];
?>
</font>
<form action=logcheck.php method=post>
User ID:<input type=text name=uid><br>
Password:<input type=password name=pass><br>
<input type=submit value=Login>
</form>
</body>
For logincheck:
<?php
$u=$_POST['uid'];
$p=$_POST['pass'];
if($u==='rkgec' && $p==='123')
{
session_start();
$_SESSION['usrid']=$u;
$_SESSION['passwd']=$p;
header("Location: home.php");
}
else
header("Location:login.php?msg=User ID or PAssword Not Match...!");
?>
For home.php
<body bgcolor=pink>
<h1>Welcome, RKGEC</h1>
<br>
<?php
session_start();
if($_SESSION['usrid']===null || $_SESSION['passwd']===null)
header('location:login.php');
echo "<font color=green><b>USER ID :$_SESSION[usrid]<br>";
echo "Password :$_SESSION[passwd]<br>";
?>
<a href=logout.php>LOGOUT</a>
</body>
While logging in, add a new element to the user's session and set its value to true.
Like so.
$_SESSION['logged_in'] = true;
And in your login page you can do a check like so.
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true)
{
header("Location: home.php");
}
Haider Ali's answer is probably better but here's a simpler way
<?php
if ($_SESSION['logged_in'] == true) {
header("Location: home.php");
} else {
header("Location: login.php");
}
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.