0

I am trying to protect 1 web page with a password. I used this code from GitHub that works pretty well for me.

Unfortunately, it doesn't expire even after days and page is still "unlocked" after first unlocking.

Please, do you have an idea how to set up a session to expire in 15 minutes?

Here is a code:

<?php
# https://gist.github.com/4692807
namespace Protect;
# Will protect a page with a simple password. The user will only need
# to input the password once. After that their session will be enough
# to get them in. The optional scope allows access on one page to
# grant access on another page. If not specified then it only grants
# access to the current page.
function with($form, $password, $scope=null) {
  if( !$scope ) $scope = current_url();
  $session_key = 'password_protect_'.preg_replace('/\W+/', '_', $scope);
  session_start();


  # Check the POST for access
  if( $_POST['password'] == $password ) {
    $_SESSION[$session_key] = true;
    redirect(current_url());
  }
  # If user has access then simply return so original page can render.
  if( $_SESSION[$session_key] ) return;
  require $form;
  exit;
}
#### PRIVATE ####
function current_url($script_only=false) {
  $protocol = 'http';
  $port = ':'.$_SERVER["SERVER_PORT"];
  if($_SERVER["HTTPS"] == 'on') $protocol .= 's';
  if($protocol == 'http' && $port == ':80') $port = '';
  if($protocol == 'https' && $port == ':443') $port = '';
  $path = $script_only ? $_SERVER['SCRIPT_NAME'] : $_SERVER['REQUEST_URI'];
  return "$protocol://$_SERVER[SERVER_NAME]$port$path";
}
function redirect($url) {
  header("Location: $url");
  exit;
}

Thank you in advance! Filip

Filip
  • 95
  • 10
  • 2
    Store the timestamp of the last access in the session, and check the difference to the current timestamp on the next request … – 04FS Jun 27 '19 at 12:13
  • 1
    Possible duplicate of [how to expire php session if user is inactive for 15 mins](https://stackoverflow.com/questions/9124560/how-to-expire-php-session-if-user-is-inactive-for-15-mins) – Shivendra Singh Jun 27 '19 at 12:21
  • 1
    @filip do you want session to be expire within 15 min even if the user active in the site or you want to session to be expired after 15 min that user logged in – Nipun Tharuksha Jun 27 '19 at 12:33
  • It is only 1 locked page. So it doesn't matter. S0 HS already figured it out. Thank you. – Filip Jun 27 '19 at 14:41

1 Answers1

1

get current time in your session when user logged in

$_SESSION['user_time']=time()

next create function and share in your pages you want to be protected

function isSessionExpired()
{
   if(time()-$_SESSION['user_time']>(15*60))
   { 
      /... your actions here for example unset session or user


   }

}

that's all!

Shkar Sardar
  • 41
  • 1
  • 4