Sesiones php

Table of Contents

Starting A Session:

Session Variables:

Destroying Session:

Increase Session Timeout In PHP:

Conclusion:

STARTING A SESSION:

session_start() is used to start a PHP session or resume the current one in the web page. It generates a unique session ID for the user.

 

session_start(); 

SESSION VARIABLES:

After the start of the session, session variables can be created for future use. It can be accessed throughout the application. You can create a session variable and store value in it with the following syntax:

 

$_SESSION['userName'] = "CodeLeaks"; 

DESTROYING SESSION:

We need to destroy the PHP session when a user logs out from the web site. To free all the session variable, the following command is used.

 

session_unset(); 

To end the complete session, following command is used.

 

session_destroy(); 

INCREASE SESSION TIMEOUT IN PHP:

You can place an upper limit on the session time by modifying those criteria if the sessions are enforced with cookies (which they almost certainly are) and the clients are not malicious. Setting session.gc_maxlifetime along with session_set_cookie_params set cookie params should function for you if you are using PHP’s default session handling with cookies. Below an example, you can use like this.

<?php

// server should keep session data for AT LEAST 1 hour

ini_set('session.gc_maxlifetime', 3600);

 

// each client should remember their session id for EXACTLY 1 hour

session_set_cookie_params(3600); 

We’ve already discussed the basic functions used for handling a session. Now, come towards the main part, which is How to increase the session timeout in PHP.

 

 

Let’s take a simple example of a login form, from which a user can log in to their account. For this, we have our database in phpMyAdmin with the name “authentication”. In this database, we have a table called “users” which has the list of all registered user names and their password.

 

User table with two fields.

First, we need to establish our connection with the database.

 

<?php

 

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "authentication";

 

// create connection

$conn = mysqli_connect($servername, $username, $password, $dbname);

 

if ($conn) {

  # code...

  // echo "Connecton Open"; 

}

else

    echo "Connection failed";

  ?> 

Our main file is index.php, having a simple login form. User has to enter his/her credential to be able to access the home page of the Web site.

 

<!DOCTYPE html>

  <html lang="en">

    <head>

        <meta charset="UTF-8">

        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap 

          /4.4.1/css/bootstrap.min.css" integrity="sha384 Vkoo8x4CGsO3+Hhxv8T 

         /Q5PaXnHiSgDznyvEWLRDTty2Ej8fUgrwm3Xjt1Q9Ifjh" crossorigin="anonymous">

        <link rel="stylesheet" href="index.css">

        <title>Log in</title>

    </head>

    <body>

      <div class="wrapper mx-auto mt-5">

        <h2 class="text-center mb-4">LOG IN</h2>

        <form method="POST" action="">

          <div class="row">

            <div class="col-12">

              <input type="text" class="form control" placeholder="User Name"               

               name="username" required>

            </div>

            <div class="col-12 mt-3">

              <input type="password" class="form-control" placeholder="Password" 

              name="password" required>

            </div>

          </div>

          <input type="submit" name="login" class="btn btn-secondary mt-4 w-100 

           login-btn" value="Log In" >

        </form>

      </div>

    </body>

  </html> 

login form tab

When a user clicks on Log In button, credentials are matched with our database record to find whether the user is registered or not.

 

If the user’s information matches then, session starts and session variables are set. A session variable $_SESSION[‘start’] is initialized to store the time of login. Another variable $_SESSION[‘expire’] calculates the time which we’ll use to destroy our session.

 

Here we multiply our 40 minutes with 60 to convert them into seconds (You can change the value 40 minutes as per your requirement). It is then directed to the home page of the web site.

 

<?php  

    include("connection.php");

    error_reporting(0);

 

    if($_POST['login']) {

      $un=$_POST['username'];

      $pass=$_POST['password'];

      

      $query = "SELECT * FROM USERS WHERE user_name='$un' AND password='$pass'"; 

      $data = mysqli_query($conn,$query);

      $total = mysqli_num_rows($data);

      if($total != 0) {

        session_start();

        $_SESSION['auth'] = true;

        $_SESSION['start'] = time();

        $_SESSION['expire'] = $_SESSION['start'] + (40 * 60);

        header('location:homePage.php');

        echo "run";

      } else {

?>

    <script>

            alert("user name or password is invalid");

        </script>

        <?php

      }

    }

   

increase session timeout in PHP

On the home page, the session_start() function is called to maintain the session. It allows us to fetch session variables from the page. An if() statement is maintained to check that someone is not directly trying to access the page without login. If this is the case, then the URL will automatically redirect to the Log in page.

 

 

 

If the user is already logged in, then the current time is stored in a variable $currentTime. The current time shouldn’t exceed the desired timeout which we calculated previously in “index.php” page. When the duration exceeds the session is destroyed, and it is redirected to the Log in page.

 

<?php

    include("connection.php");

    error_reporting(0);

    session_start();

 

    if(!$_SESSION['auth']) {

      header('location:index.php');

    }

    else {

      $currentTime = time();

      if($currentTime > $_SESSION['expire']) {

        session_unset();

        session_destroy();

        header('location:index.php');

      }

      else {

  ?>

    

  <!DOCTYPE html>

  <html lang="en">

    <head>

      <meta charset="UTF-8">

      <meta name="viewport" content="width=device-width, initial-scale=1.0">

      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4 

      .4.1/css/bootstrap.min.css" integrity="sha384Vkoo8x4CGsO3+Hhxv8T/Q5Pa

      XnHiSgDznyvEWLRDTty2Ej8fUgrwm3Xjt1Q9Ifjh" crossorigin="anonymous">

      <link rel="stylesheet" href="index.css">

      <title>Home Page</title>

    </head>

    <body>

      <div class="row no-gutters d-flex justify-content-end pr-3">

        <a href="logout.php" class="logout">

          <input type="submit" name="login" class="btn btn-secondary mt-3"  

           value="Log Out">

     </a>

      </div>

      <h1 class="text-center">Welcome to the Home Page</h1> 

    </body>

    <?php

        }

      }

    ?>

  </html>

 

Below is the PHP logout script which is used if anyone wants to log out from the page before the session timeout.

 

<?php

    session_start();

    session_unset();

    session_destroy();

    header('location:index.php');

  ?> 

CONCLUSION:

Creating a session in PHP is considered to be a fundamental element in a website. In today’s world, almost every site has a system to authenticate its user, and there could be different scenarios where the owner of the website wants to create a PHP session for a specific period. In this article, we have seen how to increase session timeout in PHP.

Detalles del artículo

ID de artículo:
41
Categoria:
Fecha de alta:
2021-10-13 00:44:16
Vistas:
182
valoración (Votar):
(4)