This post for PHP beginners Login Page Example. I want to explain creating a database, posting form values, storing the session value and destroy the session. It is very useful and simple.
You can also like the tutorial Secure PHP Login Page Example. Please go through this tutorial step by step and let me know in case you got any problem to configure PHP Login Page.
Database
MySQL users table columns id, username, password.
CREATE TABLE users
(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(30) UNIQUE,
password VARCHAR(30)
);
Database configuration file.
<?php
define("DB_SERVER", "localhost");
define("DB_USERNAME", "username");
define("DB_PASSWORD", "password");
define("DB_DATABASE", "database");
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>
Contains PHP and HTML code.
<?php
include("connection.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$myusername=mysqli_real_escape_string($db,$_POST["username"]);
$mypassword=mysqli_real_escape_string($db,$_POST["password"]);
$passwordSecure=md5($mypassword);
$sql="SELECT id FROM users WHERE username=$myusername and password=$passwordSecure";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$active=$row["active"];
$count=mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
session_register("myusername");
$_SESSION["login_user"]=$myusername;
header("location: welcome.php");
}
else
{
$error="Your Login Name or Password is invalid";
}
}
?>
<form action="" method="post">
<label>UserName :</label>
<input type="text" name="username"/><br />
<label>Password :</label>
<input type="password" name="password"/><br/>
<input type="submit" value=" Submit "/><br />
</form>
Session verification. If no session value page redirect to login.php
<?php
include("connection.php");
session_start();
$user_check=$_SESSION["login_user"];
$ses_sql=mysqli_query($db,"select username from admin where username=$user_check");
$row=mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$login_session=$row["username"];
if(!isset($login_session))
{
header("Location: login.php");
}
?>
<?php
include("user_session.php");
?>
<body>
<h1>Welcome <?php echo $login_session; ?></h1>
</body>
SignOut Destroy the session value.
<?php
session_start();
if(session_destroy())
{
header("Location: login.php");
}
?>
© 2025 Easy To Learning. All Rights Reserved | Design by Easy To Learning