how to set a session time for specific page - php

When you go to this page;
http://www.ctuchicago.com/registration/login.php
you will see the form that I made. I want to create a session if username and password is true than I wanna set a 20 minutes expire time for it. How can I do it ?
my check.php
$user = $_POST['user'];
$pass = $_POST['pass'];
$ruser = "a";
$rpass = "b";
if ($user == $ruser) {
$logn = "True";
} else {
$logn = "False";
}
if ($pass == $rpass) {
$logs = "True";
} else {
$logs = "False";
}
if ($logn == "False" && $logs == "False") {
echo '<script type="text/javascript">alert("The Username and The Password are both wrong ! Please check your information and try again.");history.go(-1);</script>';
} elseif ($logn == "True" && $logs == "False") {
echo '<script type="text/javascript">alert("The Username is True but something is wrong with the password you entered. Please check your information and try again.");history.go(-1);</script>';
} elseif ($logn == "False" && $logs == "True") {
echo '<script type="text/javascript">alert("The Password is True but something is wrong with the password you entered. Please check your information and try again.");history.go(-1);</script>';
} else {
$_SESSION['valid'] = "1";
echo '<script type="text/javascript">window.location = "http://www.ctuchicago.com/registration"</script>';
}
my index.php (this page I want to be login required.
if ($_SESSION['valid']) {
echo '<script type="text/javascript">window.location = "http://www.ctuchicago.com/registration/login.php"</script>';
} else { Code }
Thank You

According to http://prajapatinilesh.wordpress.com/2009/01/14/manually-set-php-session-timeout-php-session/
ini_set(’session.gc_maxlifetime’, 20*60);

Have you considered using a [client side] cookie that expires in 20 minutes ? then whenever the page is (re)loaded, check for the cookie, invalidate the session if the cookie is invalid/expired.

See How do I expire a session after 30 minutes
EDIT
Basically what you are doing is creating your own session timeout function. When you hit the page you look for a variable you set in $_SESSION lets call it $_SESSION['started']. If you don't find that variable then you create it and give the value of the current timestamp. What you do then is every time you load a new page, you compare the $_SESSION['started'] variable with the time now and if it exceeds 20 minutes then you expire log the user out or do whatever you need to do.

Related

Auto check for user roles on login handler instead checking with sessions on every page?

I am trying to add a login to my site. I searched on the internet for examples I found two login systems
This one and this one
I want to use the second one this one looks more complete to me. I am not a coder and I need your advice.
I do check for user role with this code on every protected page
if(!$isLoggedIn || $_SESSION["role"] != admin) {
echo "you dont have permissions to access this page";
exit();
}elseif(!$isLoggedIn || $_SESSION["role"] != normal){
echo "you dont have permissions to access this page";
exit();
}elseif(!$isLoggedIn || $_SESSION["role"] != notactive){
echo "you must update your account";
exit();
}
First question. How can I integrate above codes with cookie check in sessionCheck.php
require_once "Auth.php";
require_once "Util.php";
$auth = new Auth();
$util = new Util();
// Get Current date, time
$current_time = time();
$current_date = date("Y-m-d H:i:s", $current_time);
// Set Cookie expiration for 1 month
$cookie_expiration_time = $current_time + (30 * 24 * 60 * 60); // for 1 month
$isLoggedIn = false;
// Check if loggedin session and redirect if session exists
if(!empty($_SESSION["uid"])) {
$isLoggedIn = true;
}
// Check if loggedin session exists
else if(!empty($_COOKIE["member_login"]) && !empty($_COOKIE["random_password"]) && !empty($_COOKIE["random_selector"])) {
// Initiate auth token verification directive to false
$isPasswordVerified = false;
$isSelectorVerified = false;
$isExpiryDateVerified = false;
// Get token for username
$userToken = $auth->getTokenByUsername($_COOKIE["member_login"],0);
// Validate random password cookie with database
if(password_verify($_COOKIE["random_password"], $userToken[0]["password_hash"])) {
$isPasswordVerified = true;
}
// Validate random selector cookie with database
if(password_verify($_COOKIE["random_selector"], $userToken[0]["selector_hash"])) {
$isSelectorVerified = true;
}
// check cookie expiration by date
if($userToken[0]["expiry_date"] >= $current_date) {
$isExpiryDareVerified = true;
}
// Redirect if all cookie based validation retuens true
// Else, mark the token as expired and clear cookies
if(!empty($userToken[0]["id"]) && $isPasswordVerified && $isSelectorVerified && $isExpiryDareVerified) {
$isLoggedIn = true;
} else {
if(!empty($userToken[0]["id"])) {
$auth->markAsExpired($userToken[0]["id"]);
}
// clear cookies
$util->clearAuthCookie();
}
}
The second question which one you recommend me to use?
This should work assuming $userToken contains the role attribute.
require_once "Auth.php";
require_once "Util.php";
$auth = new Auth();
$util = new Util();
// Get Current date, time
$current_time = time();
$current_date = date("Y-m-d H:i:s", $current_time);
// Set Cookie expiration for 1 month
$cookie_expiration_time = $current_time + (30 * 24 * 60 * 60); // for 1 month
$isLoggedIn = false;
$role = null;
// Check if loggedin session and redirect if session exists
if(!empty($_SESSION["uid"])) {
$isLoggedIn = true;
$role = (isset($_SESSION["role"]) ? $_SESSION["role"] : null);
}
// Check if loggedin session exists
else if(!empty($_COOKIE["member_login"]) && !empty($_COOKIE["random_password"]) && !empty($_COOKIE["random_selector"])) {
// Initiate auth token verification directive to false
$isPasswordVerified = false;
$isSelectorVerified = false;
$isExpiryDateVerified = false;
// Get token for username
$userToken = $auth->getTokenByUsername($_COOKIE["member_login"],0);
// Validate random password cookie with database
if(password_verify($_COOKIE["random_password"], $userToken[0]["password_hash"])) {
$isPasswordVerified = true;
}
// Validate random selector cookie with database
if(password_verify($_COOKIE["random_selector"], $userToken[0]["selector_hash"])) {
$isSelectorVerified = true;
}
// check cookie expiration by date
if($userToken[0]["expiry_date"] >= $current_date) {
$isExpiryDareVerified = true;
}
// Redirect if all cookie based validation retuens true
// Else, mark the token as expired and clear cookies
if(!empty($userToken[0]["id"]) && $isPasswordVerified && $isSelectorVerified && $isExpiryDareVerified) {
$isLoggedIn = true;
$role = (isset($userToken[0]["role"]) ? $userToken[0]["role"] : null);
} else {
if(!empty($userToken[0]["id"])) {
$auth->markAsExpired($userToken[0]["id"]);
}
// clear cookies
$util->clearAuthCookie();
}
}
if (!$isLoggedIn || $role != "admin") {
echo "you dont have permissions to access this page";
exit();
} else if (!$isLoggedIn || $role != "normal") {
echo "you dont have permissions to access this page";
exit();
} else if (!$isLoggedIn || $role != "notactive") {
echo "you must update your account";
exit();
}

Login count in php

I have a login script I want if user attempt 3 invalid password then the username associated to them would be disabled or blocked for a day / 24hrs.
Since I make a if condition in php login code where status=3 alert your account is blocked for a day.
status is my database column name which count the value of invalid login of user from 1 to 3 maximum.
But issue is my here that is how I make the status automatically count or increase like 1, 2, 3 in user invalid login.
How to I add this function with my login code
I have not idea about that. On YouTube there is not any video regards this even in other website.
Stackoverflow is my last hope where someone helps user.
Please have a look at this question and help to create satatus count automatic when user inter invalid password.
My login PHP is : https://pastebin.com/QpwDtjBg
Thank you in advance
You're gonna want to use PHP's $_SESSION object.
In the code block where you detect bad user/pass combos, add an iterator to the session.
First, add a session entry to the top of your script (Or wherever you define global variables), for bad_logins, and start your session.
session_start();
$_SESSION['bad_logins'] = 0;
Then in the part of your code where you detect a bad login, increment the bad logins by 1.
$_SESSION['bad_logins']++;
This will allow you to then check for bad attempts with an if statement
if($_SESSION['bad_logins'] > 3) {
// Do something here.
}
The script you linked has some other issues you may want to address prior to adding this in though.
You just need to add an update to the field 'status' on the database with 1, 2 or 3, on the IF condition:
if($data == NULL || password_verify($password, $data['Password']) == false) {
And read that same field, when the submit form is sent every single time... if it is already 3, then just skip to the IF condition
if($data['Status'] == "//auto count//")
Something like this (haven't tested the code) and the code should be function based, at least...
`
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if(isset($_POST['submit'])) {
$messages = array(
'INVALID_EMAIL' => "<div class='alert-box warning error'><span>Invalid format, re-enter valid email.</span></div>",
'ALL_FIELDS_REQUIRED' => "All field is mandatory! case sensitive.",
'VERIFY_EMAIL' => "Please verify your email!",
'INVALID_COMBINATION' => "Invalid username or password combinations.",
'BLOCKED' => "you are blocked for a day. <a href='#'><span>Know why?<span></a>",
);
$msg = "";
$error = false;
$con = new mysqli("localhost", "softwebs_softweb", "test#123", "softwebs_cms");
$email = $con->real_escape_string(htmlspecialchars($_POST['username']));
$password = $con->real_escape_string(htmlspecialchars($_POST['password']));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$msg = $messages['INVALID_EMAIL'];
$error = true;
}
if ($email == "" || $password == "") {
$msg = $messages['ALL_FIELDS_REQUIRED'];
$error = true;
}
if(!$error) {
$sql = $con->query("SELECT * FROM users where Email_ID = '$email' ");
if ($sql->num_rows > 0) {
$data = $sql->fetch_array();
// Blocked
if ($date['status'] === 3) {
$msg = $messages['BLOCKED'];
$error = true;
}
if ($data['isEmailConfirm'] == "0") {
$msg = $messages['VERIFY_EMAIL'];
$error = true;
}
if ($data == NULL || password_verify($password, $data['Password']) == false) {
$msg = $messages['INVALID_COMBINATION'];
$error = true;
// Update the status + 1
$sql = $con->query("UPDATE users SET status = " . $statusData['status'] + 1 . " WHERE Email_ID = '$email' ");
}
}
}
if($error && trim($msg) !== "") {
$msg = "<div class='alert-box error'><span>$msg</span></div>";
} else {
session_start();
$_SESSION['login']=$_POST['username'];
$_SESSION['id']=$data['id'];
header('location: ./account/dashboard.php');
}
}
?>
`

how to get back to previous page when session time out in php

In my program i want when the session is time out after entering the login details again back to the previous page for this i am doing like this
index.php:
$PAGE_TITLE = "Sign In...";
getTitleSetting('Super');
divertAdminUser();
$index_local_url =$_SERVER['HTTP_HOST'].'/TicketRoom/public_html/test/users/index.php';
$redirect_url = $_SERVER['HTTP_REFERER'];
if(isset($_POST['seller_password']) && isset($_POST['seller_email']) && $_POST['seller_submit_x'] != '' && $_POST['seller_submit_y'] != ''){
$password=$_POST['seller_password'];
$username=check_input($_POST['seller_email']);
$db=new DbConnect($DB_HOST, $DB_USERNAME, $DB_PASSWORD, $DB_NAME,$DB_REPORT_ERROR, $DB_PERSISTENT_CONN);
$db->open() or die($db->error());
if(authenticateUser($password, $username, $db)){
$seller_id =$_SESSION['SESS_v_seller_id'];
$select_email_query=mysql_query("select * from ".TK_SELLER_USERS." where id='".$seller_id."'");
$row_seller_id = mysql_fetch_array($select_email_query);
$trading_status = $row_seller_id['status'];
$_SESSION['SESS_v_usertype'] = $row_seller_id['user'];
if($redirect_url == $index_local_url)
{
if($trading_status == "Active-pending")
{
header("location:reset_password.php");
exit;
}
else
{
if($row_seller_id['user'] == "Affiliate")
{
if($_SESSION['sts_aff'] == "P")
{
header("location:dashboard/awaiting_approval.php");
exit;
}
else
{
header("location:dashboard/current.php");
exit;
}
}
else if($row_seller_id['user'] == "Performer")
{
header("location:accountsettings/performer_index.php");
exit;
}
else if($row_seller_id['user'] == "Venu_owner")
{
// header("location:https://example.com/test/users/accountsettings/performer_index.php");
header("location:accountsettings/performer_index.php");
exit;
}
else
{
header("location:dashboard.php");
exit;`
}
}
}
else
{
header("location:".$redirect_url);
}
}
else{
$_SESSION['sess_msg'] = "Authentication failed!";
$_SESSION['sess_class']='err';
header ("Location: index.php");
exit;
}
}
i am trying to get back to previous page but it is not working properly when session time out its come back to login page
here my $redirect_url = some previous page($_SERVER['HTTP_REFERER'])
again entering the login details my $redirect_url change to login page url
$redirect_url = login page($_SERVER['HTTP_REFERER'])
so its repeat the same page and i want only for session time out not for the logout how can i do it can you explain please.
When you check the session at if session is not stored then create temp session variable and store the current URL in that.
After user login check if temp session variable is set or not. If set then get the value of that variable and redirect to that page else continue with profile / dashboard page.

PHP and AJAX Log in validation

I need some help troubleshooting my code that's used for Log In validation. It's a combo of AJAX and PHP.
Here's the AJAX code that's directly in the login page.
<script language="javascript">
$(document).ready(function()
{
$("#login_form").submit(function()
{
$("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
$.post("/ajax_login.php",{ user_name:$('#username').val(),password:$('#password').val()
,rand:Math.random() } ,function(data)
{
if (data=='no')
{
$("#msgbox").fadeTo
(200,0.1,function()
{
$(this).html('Incorrect Username or Password.')
.addClass('messageboxerror').fadeTo(900,1);
}
);
}
else if(data=='yes')
{
$("#msgbox").fadeTo
(200,0.1,function()
{
$(this).html('Logging in.....').addClass('messageboxok').fadeTo
(900,1, function()
{
document.location='/mainpage.php';
}
);
}
);
}
else
{
$("#msgbox").fadeTo
(200,0.1,function()
{
$(this).html('User is already logged in.').
addClass('messageboxerror').fadeTo(900,1);
}
);
}
});
return false;
});
$("#password").blur(function()
{
$("#login_form").trigger('submit');
});
});
</script>
PHP CODE:
<?
//Log In credentials
if ($rehash==$dboPW && $user_name == $dboUN && $logged=='Y'){echo "alreadyLogged"; exit;}
if ($rehash==$dboPW && $user_name == $dboUN && $logged=='N')
{
echo "yes";
$_SESSION['login'] = $username;
$_SESSION['password'] = $rehash;
$loggedUpdate=mysql_query("UPDATE Users SET LOGGED='Y' WHERE username='$user_name'");
exit;
}
else
{echo "no";}
?>
To summarize this process, someone logs in and the PHP script checks
if the username and password is valid AND that the person is NOT logged in already - returns value of 'yes'
if the username and password is valid AND that the person IS logged in already - returns value of 'alreadyLogged'
Invalid username or password - returns value of 'no'
This gets passed to AJAX, which SHOULD display the correct messages based on the return values from the php script. For reference (using the above summary):
AJAX should return: Logging in...
AJAX should return: User is already logged in.
AJAX should return: Invalid Username or Password.
The problem is this: If someone logs in correctly and IS NOT already logged in, message 2 appears instead of message 1. (I think that message 1 may appear but it disappears so fast).
I think the culprit is AJAX but unfortunately I'm not as familiar with it as I am with PHP.
I think the problem is with your php code.Your ajax code looks fine
try this
if ($rehash==$dboPW && $user_name == $dboUN && $logged=='Y')
{
echo "alreadyLogged"; exit;
}
elseif ($rehash==$dboPW && $user_name == $dboUN && $logged=='N')
{
}
I think it is the php problem,it occur an error and return the error message. if ajax_login.php does not return "yes" or "no" it will show the second message, whatever it returns.
Just need modify your PHP. try this :
//Log In credentials
// check if post if (isset($_POST)) {
// must initially to use check if on loggin
session_start();
// set variable post
$username = $_POST['user_name'];
$password = $_POST['password']; // change if use sha1 or md5
$rand = $_POST['rand'];
// check query database
$query = mysql_query("SELECT * FROM Users WHERE username='$username' AND password='$password'");
$user = mysql_fetch_array($query);
$row = mysql_num_rows($query);
if ($row > 0) {
if ($user['LOGGED'] == 'Y') {
echo "yes";
$_SESSION['login'] = $username;
$_SESSION['password'] = $rehash;
$loggedUpdate = mysql_query("UPDATE Users SET LOGGED='Y' WHERE username='$user_name'");
exit;
} elseif ($user['LOGGED'] == 'N') { // you can use 'else'
echo "alreadyLogged";
exit;
}
} else {
// invalid value password and username
echo "no";
exit;
} }

Php, session id control doesnt work?

here is the code drives me crazy:)
<?php
$deger=0;
if (session_id() == '') {
session_start();
$deger=1;
}
else{
$deger=0;
}
$row = mysql_fetch_row($result);
$counter =$row[2];
if($deger==1){
$counter--;
}
echo $counter;
?>
This basic code drives me crazy. the deger==1 condition always returns true and keeps decrementing the counter. What I would like to do is check the session if the session is new decrement it only once. after that dont decrement the value. Am I missing something here? I am new to php maybe I am missing something.
I look forward to your answers thanks.
i think you have to call session_start(); before any chacks like if (session_id() == '') cause theres really nothing in session_id when session has not been started. this code i one used is working for me (may be not perfect):
session_start();
$user = (isset($_SESSION['user']) && $_SESSION['user'] != '' ? $_SESSION['user'] : null);
if ($user == null) {
//it's a not logged in user
//checking users credentials and if it's ok
$_SESSION['user'] = $uid; //or whatever you want to use to identify a user
} else {
//it's logged in user
}
There is always a user session, but not always a php session. So if you did not do a session_start() yet, you can check that with something like this:
if (isset($_SESSION]['loggedin'])){
$deger = 0;
} else {
$deger = 1;
session_start();
$_SESSION['loggedin'] = true;
}
Wherever you start the session, also fill the $_SESSION var.

Categories