For Previous chapter we already know what is session and how to set and destroy.
So here, We are going to learn how to using PHP code for login page using session without stored details in database.
Php code for login page using session
Example
1. First Create login page and named as Index.php
Code
<?php session_start(); // Session start if(isset($_POST['check'])) // Check form submit with IF Isset function { $username="admin"; // set variable value $password="123"; // set variable value if($_POST['username']==$username && $_POST['password']==$password) // Check Given user name, password and Variable user name password are same { $_SESSION['username']=$username; // set session from given user name header('location:mainpage.php'); } else { $err="Authentication Failed Try again!"; } } ?> <html> <head> <title>Main Page</title> </head> <body> <Center> <?php if(isset($err)){ echo $err; } ?> <!-- Print Error --> <form method="POST" name="loginauth" target="_self"> User Name: <input name="username" size="20" type="text" /> <br/><br/> Pass Word: <input name="password" size="20" type="password" /> <br/><br/> <input name="check" type="submit" value="Authenticate" /> </form> </center> </body> </html>
Explanation
This index.php page will Set username and password as “admin” and “123”.
Check whether given user name and password is correct or wrong.
If the given username and password is correct. Set $_SESSION variables as username and redirect to mainpage.php
2. Second Create mainpage.php
Code
<?php session_start(); //session start if(!isset($_SESSION['username'])) //if session not found redirect to homepage { header('location:index.php'); } echo "Welcome "; echo $_SESSION['username']; //retrieved using session ?> <html> <head> </head> <body> <center> <h2>Welcome to Main page</h2> <a href="logout.php">logout</a> </center> </body> </html>
Explanation
Session variable retrieve the session value from index.php page to this page.
HINT : We can Use many number of pages with session variables.
<?php session_start(); //session start if(!isset($_SESSION['username'])) //if session not found redirect to homepage { header('location:index.php'); } echo "Welcome "; echo $_SESSION['username']; //retrieved using session ?>
simply place this in the top of the page.
3. Create logout.php page for destroy the session or unset the session
<?php session_start(); if(!isset($_SESSION['username'])) //if session not found redirect to homepage { header('location:index.php'); } unset($_SESSION['username']); // Session Found Unset the variable values session_destroy(); // Destroy the session header('location:index.php'); ?>
Explanation
When you click Logout.php its check the session and unset the variable values and destroy the session
Developer desks- session – Full code Download here
To know Login With session in php using stored data in MySQL database here