Javascript required
Skip to content Skip to sidebar Skip to footer

Php Session Example Login & Logout Pdf Updated FREE

Php Session Example Login & Logout Pdf

PHP Login Script with Session

by Vincy. Last modified on June second, 2021.

In this tutorial, let us create a login script with a session in PHP. Information technology has a simple example of implementing user authentication. This example uses a standard login class to get the user login details. And it preserves the login land with PHP sessions.

Login would be the first step of many application. Sometimes, part of privileged functionalities of awarding will ask users to login.

So, the login script is an integral office of an application. I will present you lot the implementation of the login system with minimal code.

Authentication will help the states to place the genuine users. By enabling authentication, nosotros can protect our website from anonymous access.

What is within?

  1. Ways to create an authentication system
  2. About this example
  3. File structure
  4. User login interface
  5. PHP code to process login
  6. Get logged-in user profile data to show a welcome message
  7. Handling logout code in PHP
  8. Database script
  9. Test login details
  10. PHP login script with session output

Ways to create an authentication organization

There are different means of implementing an authentication organization. The virtually popular way is to get the username and password via a login class and authenticate based on them.

PHP Login Script with Session

Recently, authentication using OTP is also becoming the norm. The OTP will exist dynamic and allowed for one-fourth dimension.

For OTP authentication, the application sends information technology via wither via SMS or electronic mail. In a previous article, nosotros have seen an instance code in PHP to login past sending OTP via email.

About this example

In this instance, information technology has users database with name, electronic mail, password and more details. It has a HTML form with inputs to go the user login credentials.

When the user submits their login details, then the PHP lawmaking will receive the posted data. Information technology compares the entered information confronting the user database.

If match found, then information technology sets the user login session. In this hallmark code, it preserves the user id in a PHP session. The existence of this session will state user authentication status.

Afterwards authentication, the PHP $_SESSION super global variable volition contain the user id. That is, the $_SESSION["member_id"] is set to manage the logged-in session. It volition remain until log out or quit from the browser.

While logout, nosotros unset all the session variables using PHP unset() function.

File structure

Beneath screenshot shows the organized file structure of this user login case. The Member.phpis the model class with authentication functionalities.

TheDataSource.php file contains functions to get a connection and admission database.

In aviewdirectory, I accept created all the UI related files for the login and the dashboard interface. It too contains a stylesheet used for this UI.

Theindex.php is the landing page that checks the user logged-in session. Then it redirects users either to log in or to the dashboard.

The login-activeness.phpandlogout.phpfiles are the PHP endpoints. They handle actions equally requested by the users via the interactive authentication Interface.

Login Script with Session Example File Structure

User login interface

Creating a HTML form to login is the first step. It is to get the login details from users.

In this example, it has two fields username and password for user login.

I have specified the validation role and the PHP endpoint with the form tag.

The HTML contains elements to brandish client-side validation error. Also, it has the code to prove a server-side fault response based on the login upshot.

<html> <caput> <title>User Login</title> <link href="./view/css/style.css" rel="stylesheet" blazon="text/css" /> </head> <trunk>     <div>         <form action="login-action.php" method="post" id="frmLogin" onSubmit="render validate();">             <div class="demo-table">                  <div class="form-caput">Login</div>                 <?php                  if(isset($_SESSION["errorMessage"])) {                 ?>                 <div class="fault-message"><?php  echo $_SESSION["errorMessage"]; ?></div>                 <?php                  unset($_SESSION["errorMessage"]);                 }                  ?>                 <div class="field-column">                     <div>                         <characterization for="username">Username</label><span id="user_info" grade="fault-info"></span>                     </div>                     <div>                         <input name="user_name" id="user_name" blazon="text"                             form="demo-input-box">                     </div>                 </div>                 <div grade="field-column">                     <div>                         <label for="countersign">Password</label><bridge id="password_info" grade="error-info"></span>                     </div>                     <div>                         <input name="password" id="password" blazon="password"                             class="demo-input-box">                     </div>                 </div>                 <div class=field-cavalcade>                     <div>                         <input type="submit" name="login" value="Login"                         class="btnLogin"></span>                     </div>                 </div>             </div>         </class>     </div> </body> </html>        

and the styles are,

body {     font-family: Arial;     color: #333;     font-size: 0.95em; }  .form-head {     colour: #191919;     font-weight: normal;     font-weight: 400;     margin: 0;     text-align: middle;     font-size: one.8em; }  .mistake-message {     padding: 7px 10px;     background: #fff1f2;     border: #ffd5da 1px solid;     color: #d6001c;     border-radius: 4px;     margin: 30px 10px 10px 10px; }  .demo-table {     groundwork: #ffffff;     border-spacing: initial;     margin: 15px machine;     discussion-break: break-word;     table-layout: auto;     line-height: 1.8em;     color: #333;     edge-radius: 4px;     padding: 30px;     width: 380px;     border: 1px solid;     border-color: #e5e6e9 #dfe0e4 #d0d1d5; }  .demo-table .label {     color: #888888; }  .demo-tabular array .field-column {     padding: 15px 10px; }  .demo-input-box {     padding: 13px;     edge: #CCC 1px solid;     border-radius: 4px;     width: 100%; }  .btnLogin {     padding: 13px;     groundwork-color: #5d9cec;     color: #f5f7fa;     cursor: pointer;     border-radius: 4px;     width: 100%;     border: #5791da 1px solid;     font-size: 1.1em; }  .response-text {     max-width: 380px;     font-size: 1.5em;     text-align: eye;     background: #fff3de;     padding: 42px;     border-radius: 3px;     border: #f5e9d4 1px solid;     font-family: arial;     line-height: 34px;     margin: 15px auto; }  .terms {     margin-bottom: 5px; }  .dashboard {     background: #d2edd5;     text-align: center;     margin: 15px auto;     line-height: ane.8em;     color: #333;     border-radius: 4px;     padding: 30px;     max-width: 400px;     border: #c8e0cb 1px solid; } .fault-info {     colour: #FF0000;     margin-left: 10px; } a.logout-button {     color: #09f; }        

Login form validation

This script is for validating the login data at the client-side. If the users submit the login with empty fields then this script volition return boolean false.

When it returns false, information technology displays a validation error message to the users. By returning boolean 0, the class validation script prevents login to go on further.

          <script>     function validate() {         var $valid = true;         document.getElementById("user_info").innerHTML = "";         document.getElementById("password_info").innerHTML = "";                  var userName = document.getElementById("user_name").value;         var password = document.getElementById("password").value;         if(userName == "")          {             certificate.getElementById("user_info").innerHTML = "required";         	$valid = false;         }         if(password == "")          {         	document.getElementById("password_info").innerHTML = "required";             $valid = false;         }         return $valid;     }     </script>        

PHP lawmaking to process login

The login-action.php file receives and handles the posted login data. It sends the username and countersign to the processLogin() function.

This method gets the login details and compares with the user database.

It prepares query and binds the login params with it to detect the match from the database. If friction match found the processLogin will return the result.

On successful login, the login-activeness.php sets the logged-in user session. Otherwise, information technology will return mistake past saying "Invalid Credentials".

<?php namespace Phppot;  use \Phppot\Member; if (! empty($_POST["login"])) {     session_start();     $username = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);     $password = filter_var($_POST["password"], FILTER_SANITIZE_STRING);     require_once (__DIR__ . "./class/Member.php");          $fellow member = new Member();     $isLoggedIn = $member->processLogin($username, $password);     if (! $isLoggedIn) {         $_SESSION["errorMessage"] = "Invalid Credentials";     }     header("Location: ./index.php");     exit(); }        

Go logged-in user profile information to display a welcome bulletin

This code is to display the dashboard after login. The PHP code embedded with this HTML is for getting the user session and the user data from the database.

It displays the welcome message by addressing the user with their display proper noun.

The dashboard contains a logout link in addition to the welcome text.

<?php namespace Phppot;  use \Phppot\Member;  if (! empty($_SESSION["userId"])) {     require_once __DIR__ . './../course/Member.php';     $member = new Fellow member();     $memberResult = $member->getMemberById($_SESSION["userId"]);     if(!empty($memberResult[0]["display_name"])) {         $displayName = ucwords($memberResult[0]["display_name"]);     } else {         $displayName = $memberResult[0]["user_name"];     } } ?> <html> <head> <title>User Login</title> <link href="./view/css/mode.css" rel="stylesheet" type="text/css" /> </head> <trunk>     <div>         <div class="dashboard">             <div class="member-dashboard">Welcome <b><?php repeat $displayName; ?></b>, You have successfully logged in!<br>                 Click to <a href="./logout.php" class="logout-button">Logout</a>             </div>         </div>     </div> </body> </html>

Fellow member.php

This is the PHP course created in this example to handle the login process. The getMemberById method asking DataSource to fetch the member results.

<?php namespace Phppot;  apply \Phppot\DataSource;  class Member {      private $dbConn;      individual $ds;      office __construct()     {         require_once "DataSource.php";         $this->ds = new DataSource();     }      function getMemberById($memberId)     {         $query = "select * FROM registered_users WHERE id = ?";         $paramType = "i";         $paramArray = array($memberId);         $memberResult = $this->ds->select($query, $paramType, $paramArray);                  return $memberResult;     }          public function processLogin($username, $countersign) {         $passwordHash = md5($countersign);         $query = "select * FROM registered_users WHERE user_name = ? AND countersign = ?";         $paramType = "ss";         $paramArray = array($username, $passwordHash);         $memberResult = $this->ds->select($query, $paramType, $paramArray);         if(!empty($memberResult)) {             $_SESSION["userId"] = $memberResult[0]["id"];             return true;         }     } }        

Redirect users to Login or Dashboard based on Session

A landing page index.php contains code to check logged-in session and route users appropriately. The following lawmaking shows how to redirect users based on the session.

<?php session_start(); if(!empty($_SESSION["userId"])) {     require_once './view/dashboard.php'; } else {     require_once './view/login-course.php'; } ?>        

Handling logout in PHP

By clicking the logout link from the dashboard, it calls this PHP script. In this script, it clears the current login session and redirects users back to the login. The logout lawmaking is,

<?php  session_start(); $_SESSION["user_id"] = ""; session_destroy(); header("Location: index.php");        

DataSource.php

This class establishes a connection object to access the database based on the request. Information technology has theselect role to prepare a fetch query to return the results.

<?php namespace Phppot;  /**  * Generic datasource class for handling DB operations.  * Uses MySqli and PreparedStatements.  *  * @version 2.iii  */ class DataSource {      // PHP 7.1.0 visibility modifiers are allowed for form constants.     // when using to a higher place 7.1.0, declare the below constants as private     const HOST = 'localhost';      const USERNAME = 'root';      const PASSWORD = '';      const DATABASENAME = 'phpsamples';      private $conn;      /**      * PHP implicitly takes care of cleanup for default connection types.      * So no need to worry about endmost the connectedness.      *      * Singletons not required in PHP as there is no      * concept of shared memory.      * Every object lives only for a request.      *      * Keeping things simple and that works!      */     function __construct()     {         $this->conn = $this->getConnection();     }      /**      * If connection object is needed use this method and become admission to it.      * Otherwise, use the below methods for insert / update / etc.      *      * @render \mysqli      */     public part getConnection()     {         $conn = new \mysqli(self::HOST, self::USERNAME, cocky::PASSWORD, self::DATABASENAME);                  if (mysqli_connect_errno()) {             trigger_error("Problem with connecting to database.");         }                  $conn->set_charset("utf8");         return $conn;     }      /**      * To become database results      * @param string $query      * @param cord $paramType      * @param array $paramArray      * @return array      */     public function select($query, $paramType="", $paramArray=array())     {         $stmt = $this->conn->set($query);                  if(!empty($paramType) && !empty($paramArray)) {             $this->bindQueryParams($stmt, $paramType, $paramArray);         }                  $stmt->execute();         $result = $stmt->get_result();                  if ($outcome->num_rows > 0) {             while ($row = $result->fetch_assoc()) {                 $resultset[] = $row;             }         }                  if (! empty($resultset)) {             render $resultset;         }     }          /**      * To insert      * @param cord $query      * @param string $paramType      * @param assortment $paramArray      * @render int      */     public function insert($query, $paramType, $paramArray)     {         print $query;         $stmt = $this->conn->prepare($query);         $this->bindQueryParams($stmt, $paramType, $paramArray);         $stmt->execute();         $insertId = $stmt->insert_id;         render $insertId;     }          /**      * To execute query      * @param string $query      * @param string $paramType      * @param array $paramArray      */     public function execute($query, $paramType="", $paramArray=array())     {         $stmt = $this->conn->prepare($query);                  if(!empty($paramType) && !empty($paramArray)) {             $this->bindQueryParams($stmt, $paramType="", $paramArray=array());         }         $stmt->execute();     }          /**      * i. Prepares parameter binding      * ii. Bind prameters to the sql statement      * @param string $stmt      * @param cord $paramType      * @param array $paramArray      */     public office bindQueryParams($stmt, $paramType, $paramArray=array())     {         $paramValueReference[] = & $paramType;         for ($i = 0; $i < count($paramArray); $i ++) {             $paramValueReference[] = & $paramArray[$i];         }         call_user_func_array(array(             $stmt,             'bind_param'         ), $paramValueReference);     }          /**      * To get database results      * @param string $query      * @param cord $paramType      * @param assortment $paramArray      * @render array      */     public function numRows($query, $paramType="", $paramArray=array())     {         $stmt = $this->conn->prepare($query);                  if(!empty($paramType) && !empty($paramArray)) {             $this->bindQueryParams($stmt, $paramType, $paramArray);         }                  $stmt->execute();         $stmt->store_result();         $recordCount = $stmt->num_rows;         return $recordCount;     } }        

Database script

This script contains the CREATE statement for theregistered_userstable. Likewise, it has the data dump to check the example with examination login details.

-- -- Tabular array structure for table `registered_users` --  CREATE Table `registered_users` (   `id` int(8) NOT Null,   `user_name` varchar(255) NOT NULL,   `display_name` varchar(255) Non NULL,   `password` varchar(255) Non Aught,   `email` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;  -- -- Dumping data for tabular array `registered_users` --  INSERT INTO `registered_users` (`id`, `user_name`, `display_name`, `countersign`, `email`) VALUES (1, 'kate_91', 'Kate Winslet', 'ad5611358209efdc202d35127a160748', 'kate@wince.com');  -- -- Indexes for tabular array `registered_users` -- Change Tabular array `registered_users`   ADD PRIMARY KEY (`id`);   -- -- AUTO_INCREMENT for tabular array `registered_users` -- Alter Table `registered_users`   MODIFY `id` int(8) Non Cipher AUTO_INCREMENT, AUTO_INCREMENT=4; COMMIT;        

Test login details

Later on setting this example lawmaking and database in your estimator, use the following test data to check the example login system.

Username:          kate_91        
Password:          kate@03                  

PHP login script with session output

This output screenshot shows the login course interface. It has the input fields to get the user login details.

User Login Form Screenshot

This is the screenshot of the welcome bulletin. One time logged-in, then the user will see this response in the browser.

This view volition show a welcome message by addressing the logged-in user. It likewise has a link to logout as shown below.

User Dashboard Output

Download

↑ Back to Meridian

Php Session Example Login & Logout Pdf

DOWNLOAD HERE

Source: https://phppot.com/php/php-login-script-with-session/

Posted by: hogananabrons1942.blogspot.com