When a user types in the address bar the home.php
URL, it opens and displays the home page.
I want to prevent users from accessing the home page unless they are logged in.
Below is what I've tried:
<?php
if ( isset( $_POST['btn_submit'] ) ) {
$password = $_POST['txt_pass'];
if ( $password == '123' ) {
header( "Location: home.php" ); //home.php
} else {
header( "location: index.php" );
}
}
How can I achieve that?
You can use the PHP function defined to limit access to a page if a variable isn't set.
eg
<?php defined('userstatus') OR exit('No direct script access allowed');
rest of your code here
Use this in your home.php and look for a variable you've got in a session or passed to the page.
<?php
session_start();
if(isset($_POST['btn_submit'] || !$_SESSION['userlogin']))
{
$password=$_POST['txt_pass'];
if($password=='123')
{
$_SESSION['userlogin'] = true;
header("Location: home.php"); //home.php
}else{
header("location: index.php");
}
}
?>
You can make a sessions and if the user login it's be:
$_SESSION["user"] = "true" ;
your code will be like :
<?php
if($_SESSION["user"] = "true"){
if(isset($_POST['btn_submit']))
{
$password=$_POST['txt_pass'];
if($password=='123')
{
header("Location: home.php"); //home.php
}
else {
header("location: index.php");
}
}
}
else {
header("/");
}
?>
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.