Timeout Session When There's No Activity From the User - php

how can I timeout a session when there is no activity from the user?
Here is my code which has the name session.php:
<?php
require_once('conn.php');
session_start();
$user_check = $_SESSION['login_user'];
$ses_sql = mysqli_query($conn, "select * from employee where Username = '$user_check'");
$row = mysqli_fetch_array($ses_sql, MYSQLI_ASSOC);
$login_session = $row['EmployeeName'];
if (!isset($_SESSION['login_user'])) {
header("location:index.php");
}
?>

Include this code into the profile page you want to redirect to after logged in. First calculate the time like this.
<script>
var sec = 0;
var min = 0;
var hrs = 0;
function time () {
if (sec<=59) {
sec++;
if (sec<10) {
sec="0"+sec;
}
if (sec>59) {
sec=0;
min++;
if (min>59) {
min=0;
hrs++;
if (hrs>24) {
hrs=0;
};
};
};
};
document.getElementById("time").innerHTML=hrs+":"+min+":"+sec;
}
function tick () {
if (min<10) {
min="0"+min;
}
if (hrs<10) {
hrs="0"+hrs;
}
}
window.onload=function () {
tick();
setInterval(time,1000);
}
</script>
This will give you a time. After that do this. Let's assume you want to time it out in 30 seconds. Here login.php is any common page which redirects after logout.
<script>
if(sec == 30){
</script>
<?php
$_SESSION["login_user"] = NULL;
redirect_to("login.php");
?>
<script>
}
</script>
I hope this would work.

Related

Ajax + mysql reload page

i try to work on something but it's not realy working as i want, so first we have the index page with the ajax code :
function redirect(){
$(".redirect").load("redirect.php");
}
setInterval(function(){
redirect()
}, 3000);
</pre>
Of course in the body we have this :
<div class="redirect"></div>
In the redirect.php code, we have this :
<?php
session_start();
include('db.php');
$query = "SELECT * FROM db WHERE client=".$_SESSION['clientvict']."";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$redirect = $row["redirect"];
if($redirect == 1) {
//header('location: '.$_SESSION['redirect_url']);
}
}
}
Okay so, to start, when my client is on the index.php, the row redirect is on 0.
And on my web panel, i can set up the value to 1, if the value is on 1, i want the client to be redirected of the index page to my $_SESSION['redirect_url'].
But the problem is, of course, it redirect only in the class="redirect" div.
But i want him to be redirected from the index page, so i tried in the redirect.php code this :
<?php
session_start();
include('db.php');
$query = "SELECT * FROM db WHERE client=".$_SESSION['clientvict']."";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$redirect = $row["redirect"];
if($redirect == 1) {
$ok = 1;
}
}
}
And on the index.php page i added this below the class redirect div :
<?php
if($ok == 1) {
header('location: url');
}
?>
But it doesn't detect the $ok from the redirect.php.
Any idea how i could fix this problem ?
Thank !
Okay i resolved the problem, i don't know if it's the proper way to do it, but it's working as i want ! i did that :
redirect.php :
<?php
session_start();
include('db.php');
$query = "SELECT * FROM db WHERE client=".$_SESSION['ccvict']."";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$redirect = $row["redirect"];
if($redirect == 1) {
echo '<div id="content"><div id="activity">1</div></div>';
}
else {
echo '<div id="content"><div id="activity">0</div></div>';
}
}
}
And the AJAX in index.php :
<script>
$(document).ready(function() {
function redirect(){
$.ajax({
url:'redirect.php',
type:'GET',
success: function(data){
var active = $(data).find('#activity').html();
if(active == 1) {
<?php echo 'window.location.replace("'.$_SESSION['redirect_payment'].'");'; ?>
}
}
});
}
setInterval(function(){
redirect()
}, 3000);
});
</script>
Hope it will help, thank #CBroe

user still can login although password and username is wrong

this problem make me confuse why user still can login although username and password is wrong. I don't have any idea in this problem. i try build android with ionic framework
this my controller
**
.controller('LoginCtrl', function ($scope, kaka, $ionicPopup, $state, Varlogin) {
$scope.loginData = {};
$scope.proseslogin = function () {
kaka.loginUser($scope.loginData.username, $scope.loginData.password).success(function (data) {
if (data.length > 0) {
Varlogin.setObject(data[0]);
var alertPopup = $ionicPopup.alert({
title: 'Selamat Datang',
template: 'Perikasa keadaan motor anda!'
});
$state.go('app.home');
} else {
var alertPopup = $ionicPopup.alert({
title: 'Login Gagal!',
template: 'Periksa Username dan Password anda!'
});
}
}).error(function (data) {
});
};
$scope.register = function () {
$state.go('register');
};
})
**
and this my php
**
if($function == "login" ){
$sql = mysqli_query($con, "select * from login where username='$w5'")or die(mysqli_error($con));
$row = mysqli_fetch_assoc($sql);
$pass = $row['hash_password'];
$hash_password = password_verify($w6, $pass);
if($hash_password == TRUE) {
$sqlcode = $con->query("select * from login where username='$w5' AND hash_password='$pash' AND aktif='Y'", MYSQLI_USE_RESULT);
$jsonObj = array();
while ($result = mysqli_fetch_object($sqlcode)) {
$jsonObj[] = $result;
echo "Berhasil";
}
}else {
echo "gagal";
mysqli_close($con);
}
}
**
please help my problem

how to use user id stored in session with ajax

When the user login I am storing the userid into session and then I want to pass that user id to the ajax to retriever other information form the data base.
userid stored in session is not being passed to allResult.php
My login page code snippet where i make the session:
$msg = '';
if (isset($_POST['login']) && !empty($_POST['username'])
&& !empty($_POST['password']))
{
$username1 = $_POST['username'];
$password1 = $_POST['password'];
$password2 = md5($password1);
$sql= "SELECT * FROM users WHERE userName='$username1' AND password='$password2'";
if($query_run = mysqli_query($conn, $sql))
{
$query_num_rows = mysqli_num_rows($query_run);
$stmt =mysqli_prepare($conn, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if($query_num_rows==1)
{
$row = mysqli_fetch_assoc($query_run);
$user_id = $row['id'];
$name=$row['Name'];
//creating session
$_SESSION['loggedin_time'] = time();
$_SESSION['userid'] = $user_id;
$_SESSION['name'] = $name;
}
}
else {
$msg = '*Wrong username or password';
}
}
Now after login the user will be taken to dashboard:
<?php
session_start();
include("functions.php");
if(isset($_SESSION["userid"])) {
if(isLoginSessionExpired()) {
header("Location:loginPage.php");
}
}
if($_SESSION['userid']=="" && $_SESSION['name']==""){
header("location: loginPage.php");
}
require 'dbconnect.php';
$userId = $_SESSION['userid'];
echo "$userId";
?>
in the dashboard i am trying to access the other data of the user with ajax
<script id="source" language="javascript" type="text/javascript">
$(function() {
$( "#tabs" ).tabs({active:0});
$.ajax({
url: 'allResult.php',
method:"POST",
data: ({uid:'$userId'}),
dataType: 'json',
success: function(data)
{
var date= data[0]['date'];
var time= data[0]['time'];
var ip= data[0]['ip'];
var lux= data[0]['lux'];
var press= data[0]['press'];
var acc_x= data[0]['acc_x'];
var acc_y= data[0]['acc_y'];
var acc_z= data[0]['acc_z'];
$("#tabs-1").html("<b>date: </b>"+date+"<b> time: </b>"+time+"<b> ip: </b>"+ip+"<b> lux: </b>"+lux+"<b> press: </b>"+press+"<b> acc_x: </b>"+acc_x+"<b> acc_y: </b>"+acc_y+"<b> acc_z: </b>"+acc_z);
} ,
error : function(request,error)
{
alert (error);
alert("Request: "+JSON.stringify(request));
}
});
});
I need to get the user id in order to run allResult.php
allResult.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'dbconnect.php';
$user_id = $_POST["uid"]
$sql_query = "SELECT * FROM data where id like '$user_id';";
$result = mysqli_query($conn,$sql_query);
if(mysqli_num_rows($result) >0 )
{
$row = mysqli_fetch_assoc($result);
$output [] = $row ;
echo json_encode($output);
}
else
{
echo "Error finding data..";
}
?>
Make all your user logged in data to be called into a json format.
Assuming you have all data under
somedomain.com/userData.php
<?php
#userData.php
if ($user == "loggedin") {
$data['name'] = $_SESSION[1]; //name
$data['email'] = $_SESSION[2]; //email
$data['extra'] = $_SESSION[3]; //etc.
echo json_encode($data, JSON_PREETY_PRINT);
}
?>
Then get data into realtime using jQuery Ajax.
Looks like you're missing session_start()

Issues with long polling and sessions (chat)

I made a friends chat that uses textfiles to store data and it all works more or less except when I sign in and write something to someone, nothing pops up (but the text is stored in the appropriate text file), then when I refresh the page it is ok from THEN ON, but on the other browser as the other user I have to also refresh the page in order for it to work normally both ways.
Basically, every time I log in I have to click the name of the person I want to chat with, then a window pops out and THEN i have to refresh or else it doen\sn't work.
I guess I have to kind of refresh the page whenever I click on a friend and want to chat with him and that it is a session problem.
here is home.php (users are redirected here when they log in on index.php page)
<?php
session_start();
if (!isset($_SESSION['user'])) {
header("Location: index.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">#import 'custom_chat.css';</style>
</head>
<body>
<h2>Hello, <?php echo $_SESSION['user']; ?></h2>
<hr>
<p><b>CONTACTS:</b></p>
<?php
require_once 'dbc.php';
$u = $_SESSION['user'];
$q = "SELECT user_id FROM users WHERE username='$u'";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
// current user id
$uid = $row[0];
$q = "SELECT u.username FROM users AS u, friends AS f
WHERE (f.f1 = '$uid' OR f.f2 = '$uid') AND (f.f1 = u.user_id OR f.f2 = u.user_id) AND (u.username != '$u')";
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_assoc($r)) {
echo '<div class=chat_contacts>';
echo '<div class='.$row['username'].'>';
echo '<div class=inner>';
echo '<div class=inner_chat></div>';
echo '<form>
<textarea class=chat_text></textarea>
</form>
';
echo '</div>'; // end .inner
echo '<a href="#" class='. $row['username'] .'>'.$row['username'] .'</a>
</div>';
echo '</div>'; // end .chat_contacts
}
?>
<p>HOME</p>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript">
var nc = '<?php echo $u ?>';
// toggle chat window
$('.chat_contacts a').click(function() {
$(this).prev('div.inner').toggle();
var tc = $(this).attr('class');
$(this).parent().parent().addClass(nc+tc);
$('textarea').focus(); // MD maybe
return false;
});
// call main chat function
$(function () {
updateChat();
}); // end ready
//update on enter
$('textarea.chat_text').keypress(function(e) {
$this = $(this); // textarea
if (e.which == '13') {
insertChat();
return false;
}
});
function insertChat() {
var text = $this.val();
$this.val('');
var ru = $this.parent().parent().parent().attr('class');
$.post('insert.php',{text:text, ru:ru}, function(data) {
if (data) {
alert(data)
}
});
}
var timestamp = 0;
function updateChat() {
$.ajax({
type: 'GET',
url: 'update.php?timestamp=' + timestamp,
async: true,
cache: false,
success:function(data) {
// alert(data);
var json = eval('('+data+')');
// if (json['msg'] != null) {
$('.chat_contacts.'+nc+json['nru']+' .inner_chat').append('<p>'+json['msg']+'</p>'); // MD
// }
timestamp = json['timestamp'];
setTimeout('updateChat()', 1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// alert('error '+textStatus+'('+errorThrown+')');
setTimeout('updateChat()', 1000);
}
});
}
</script>
</body>
</html>
update.php
<?php
session_start();
require_once('dbc.php');
error_reporting(E_ALL ^ E_NOTICE);
set_time_limit(0);
$ou = $_SESSION['user'];
$ru = $_SESSION['ru'];
session_write_close();
$q = "SELECT * FROM chats WHERE
(chats.f1='$ru' AND chats.f2='$ou') OR (chats.f1='$ou' AND chats.f2='$ru') ORDER BY time DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
// $filename = 'vojaolja.txt';
$q = "SELECT user_id FROM users WHERE username='$ou'
ORDER BY user_id DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
$fu = $row[0];
$q = "SELECT user_id FROM users WHERE username='$ru' ORDER BY user_id DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
$su = $row[0];
$q = "SELECT username FROM users WHERE username='$ru' ORDER BY user_id DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
$nru = $row[0];
if ($fu < $su) {
$filename = $fu.$su.'.txt';
} else {
$filename = $su.$fu.'.txt';
}
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif = filemtime($filename);
}
$response = array();
$data = file($filename);
$line = $data[count($data)-1];
$response['msg'] = $line;
$response['nru'] = $nru;
$response['timestamp'] = $currentmodif;
echo json_encode($response);
?>
Also, if someone wants to reproduce this on their own computer, I can post all the code here, it is just a few pages, it can be setup together with the database in literally 2 minutes.
EDIT:
as soon as I login, i see the following in the console:
http://localhost/x_super_chat/update.php?timestamp=0&_=1374509358392 (plus the rolling thingy, it is waiting)
Then i click on a friend's name, window pops up, I write something and i get this in the console:
http://localhost/x_super_chat/insert.php
AND THEN WHEN I REFRESH AGAIN (when it actually starts working) I get the following in the console.
http://localhost/x_super_chat/update.php?timestamp=0&_=1374509491493
http://localhost/x_super_chat/update.php?timestamp=1374509435&_=1374509493231 + the waiting thingy icon, it is waiting
So it changes after refresh, I need what I get after refresh to be there as soon as I log in.
EDIT 2: (after Pitchinnate's answer)
As soon as I login, I see this in the console:
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566749185 (plus the waiting animation)
Then I write something to the other person (say John), and I get the following:
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566749185
http://localhost/x_super_chat/insert.php
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566817682
http://localhost/x_super_chat/update.php?timestamp=1374565160&_=1374566817740
http://localhost/x_super_chat/update.php?timestamp=1374566817&_=1374566817801 (plus waiting animation)
THEN when I write something on the other side as John, I get the following: (this is from chrome so it is not the same as the console in firebug):
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566987051
http://localhost/x_super_chat/insert.php
http://localhost/x_super_chat/update.php?timestamp=1374566995&_=1374567004175
http://localhost/x_super_chat/update.php?timestamp=1374567004&_=1374567004215
One thing you can try is cancelling your long poll upon insert, create a global javascript variable outside your update function var myajax;
myajax = $.ajax({
type: 'GET',
url: 'update.php?timestamp=' + timestamp,
Then on insert:
function insertChat() {
myajax.abort();
var text = $this.val();
$this.val('');
var ru = $this.parent().parent().parent().attr('class');
$.post('insert.php',{text:text, ru:ru}, function(data) {
if (data) {
updateChat();
}
});
}

My login jquery is not calling the php file correctly

Hey im trying to write code for a login system, this is my first time and i used a tutorial online. The initial Javascript works fine and the errors show up when the inputs are left empty. However when i enter text in the inputs and click sign in, nothing happens. It seems to me like it is not calling the PHP file but i can't see any reason why it wouldnt as it is referenced correctly? Any help would greatly appreciated!
<?php
include ("Includes/dbConnect.php");
$u=$_POST['u'];
$p=$_POST['p'];
//Strip slashes
$u = stripslashes($u);
$p = stripslashes($p);
//Strip tags
$u = strip_tags($u);
$p = strip_tags($p);
$check = mysqli_query("SELECT * FROM Login WHERE login_user ='$u' AND login_pass='$p'") or die(mysqli_error());
$check = mysqli_num_rows($check);
if($check !=="0"){
$results = mysqli_query("SELECT * FROM Login WHERE login_user = '$u'") or die(mysqli_error());
while ($row = mysqli_fetch_assoc($results)) {
$login_user=$row['login_user'];
session_register('login_user');
$_SESSION['login_user'] = $Login_user;
echo "1";
}
}
?>
and here's the javascript
<script type="text/javascript">
$(document).ready(function () {
$(".sign_b_btn").live("click", function () {
var u = $("#u").val();
var p = $("#p").val();
if (u == "") {
$("#u").css("border-color", "red");
$("#un").css("color", "red");
$(".error").show().html("Please enter your username!");
$("#p").css("border-color", "#606060");
$("#up").css("color", "#333333");
} else if (p == "") {
$("#u").css("border-color", "#606060");
$("#un").css("color", "#606060");
$(".error").show().html("Please enter your Password!");
$("#p").css("border-color", "red");
$("#up").css("color", "red");
} else {
dataString = 'u=' + u + '&p=' + p;
$.ajax({
type: "POST",
url: "Ajax/login_php.php",
data: dataString,
cache: false,
success: function (html) {
if (html == "") {
$(".error").show().html("The username or password you entered is incorrect!");
$("#p,#u").css("border-color", "red");
$("#up,#un").css("color", "red");
} else if (html == "1") {
$(".error").fadeOut(1000);
$("#u").css("border-color", "#606060");
$("#un").css("color", "#333333");
$("#p").css("border-color", "#606060");
$("#up").css("color", "#333333");
$(".center").animate({
opacity: 0.25,
left: '+=900',
height: 'toggle'
}, 5000, function () {
$(".done").slideDown(200).html("Welcome " + u);
setTimeout(function () {
var u = $("#u").val("");
var p = $("#p").val("");
window.location = "index.php";
}, 5000);
});
}
}
});
}
});
});
</script>
Answer to your session problem:
edit your php code so that your script starts off with a call to session_start();
eg:
<?php session_start();
//rest of your php code
replace the lines :
session_register('login_user');
$_SESSION['login_user'] = $Login_user;
with:
$_SESSION['login_user'] = $Login_user;
You were getting the error that you mentioned because the function session_register(); has been deprecated in PHP version 5.3.0 and REMOVED from PHP version 5.4.0. $_SESSION is a global array that is available for you after session_start(); call.
Happy programming :)
thanks for the help guys, really helped me figure it out. Finished code if anyones interested:
<?php
include ("../Includes/dbConnect.php");
$u=$_POST['u'];
$p=$_POST['p'];
//Strip slashes
$u = stripslashes($u);
$p = stripslashes($p);
//Strip tags
$u = strip_tags($u);
$p = strip_tags($p);
$query = "SELECT * FROM Login WHERE login_user ='$u' AND login_pass='$p'";
$check = mysqli_query($cxn,$query) or die("Couldn't execute query!");
$check = mysqli_num_rows($check);
if($check !=="0"){
$results = mysqli_query($cxn,"SELECT * FROM Login WHERE login_user = '$u' AND login_pass='$p'") or die("Couldn't execute query2!");
while ($row = mysqli_fetch_assoc($results)) {
$username= $u;
session_register('Login');
$_SESSION['user'] = $username;
echo "1";
}
}
?>

Categories