On browser close logout - php

There are many questions asked about this problem but i suppose none of them could help me in my case. I will show you my login form , my main page, showing active users , and am little confused about starting lastTimeUpdate function to it.
Here is my main contetnt form, the problem is that there is a list of active users if user is active his name is displayed if not - not displayed, but if user exits browser, session destroys, but doesnt log out:
<?php
include 'config.php';
//include 'logout.php';
$query = "SELECT * FROM userinfo WHERE `ifactive` = 1";
if(isset($_SESSION['uname'])){
$result = mysql_query($query);
echo "<div id=maincontenttopleft>
<p>Active users</p>";
echo "<div id=acuser><table id=activeusers>";
while($row = mysql_fetch_array($result)){
echo "</td><td>" . $row['name'] . "</td></tr>";
}
echo "</table></div>";
mysql_close();
}
//if (session_destroy()) {
//mysql_query("SELECT * FROM `userinfo` WHERE `ifactive` = 1 AND `uname` !=
'$_SESSION[uname]'");
//mysql_query("UPDATE `userinfo` SET `ifactive` = 0 WHERE `uname` !=
'$_SESSION[uname]'") or die(mysql_error());
//}
if (!isset($_SESSION['uname'])) {
$_SESSION['uname'] = time();
} else if (time() - $_SESSION['uname'] > 10) {
// session started more than 30 minutes ago
//mysql_query("SELECT * FROM `userinfo` WHERE `ifactive` = 1 AND `uname` =
'$_SESSION[uname]'");
//mysql_query("UPDATE `userinfo` SET `ifactive` = 0 WHERE `uname` =
'$_SESSION[uname]'") or die(mysql_error());
session_regenerate_id(true); // change session ID for the current session an
invalidate old session ID
$_SESSION['uname'] = time(); // update creation time
}
?>
I want to check if there is a destroyed session, to take the name of this session end according to the name to set my boolean (ifactive) to zero. Can you help me about the logic of it.

You'll then need to save the session_id of every user in the database.
And then inside a cron for instance, have a script checking the existence of the file associated to each session.
Here is how you find your sessions folder if you don't want to mess in your config files :
<?php
echo session_save_path ();
?>
Your cron script could then save the results in a txt file which would be easier for your website script to read (or better yet, save it in memory so it's faster - checkout redis).

Related

SESSION Loop that increments counter

My session checks if a user is logged , however when I refresh the page the session test runs again and starts to execute the code which then adds +1 to the members online counter everytime . I would like my code to check if the session is true like below but not if I refresh the page or navigate to another page .(Only Once per login) How can this be possible ?
PS MY code is not secure My code is not in any live environment , Security will be applied later to prevent sql injection .
include('..\db.php');
$con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname);
$guest_timeout = time() -1 * 60;
$member_timeout = time() -2 * 60;
$guest_ip = $_SERVER['REMOTE_ADDR'];
$time = time()
// This session check adds +1 to my member online counter when page is reloaded
if(isset($_SESSION['CurrentUser'])){
//if user is logged
$sqlt = mysqli_query($con,"DELETE * FROM active_guests WHERE guest_ip='".$guest_ip."'");
$sqlt2 = mysqli_query($con,"REPLACE INTO active_members VALUES ('".$_SESSION['CurrentUser']."','".$time."')");
}else{
//if user not logged
$sqlt3 = mysqli_query($con,"REPLACE INTO active_guest (guest_ip,time_visited)VALUES ('".$guest_ip."','".$time."')");
}
$sqlt4 = mysqli_query($con,"DELETE * FROM active_guest WHERE time_visited < ".$guest_timeout);
$sqlt5 = mysqli_query($con,"DELETE * FROM active_members WHERE time_visited < ".$member_timeout);
$sqlt6 = mysqli_query($con,"SELECT guest_ip FROM active_guests");
$online_guests = mysqli_num_rows($sqlt6);
$sqlt7 = mysqli_query($con,"SELECT username FROM active_members");
$online_members = mysqli_num_rows($sqlt7);
?>
<div class="container">
<p>online Guests : <?php echo $online_guests ; ?></p>
<p>online Members : <?php echo $online_members ; ?></p>
</div>
You need a unique index on the username column so that REPLACE will replace instead of inserting a duplicate row.
ALTER TABLE active_members ADD UNIQUE INDEX (username);
You probably also need a unique index on the guest_ip column of active_guests, although it's possible that multiple users could be coming from the same IP.

Getting user data from session

I made a login system and it works but I also have the user's session in the page after login.
How can I get user data from my database by referencing the user's session, and how can I update it when the user put what they going to change
<?php
session_start();
$query=mysql_query("SELECT username, email, password FROM user WHERE username = $_SESSION['username']");
while($row = mysql_fetch_array( $query )) {
echo .row['username'];
echo .row['email'];
echo .row ['password'];
?>
In new codes you should be using mysqli if your PHP version is high enough (if not... update...)
But here you go:
<?php
session_start();
$query = mysql_query("SELECT * FROM user WHERE username = {$_SESSION['username']}");
$row = mysql_fetch_assoc($query);
echo $row['username'];
echo $row['email'];
echo $row ['password'];
?>
Oh and the update:
<?php
$query = mysql_query("UPDATE user SET username={$_POST['username']}, email={$_POST['email']}, password={$_POST['password']} WHERE username={$_SESSION['username']}");
?>
And you should make a form for that..
The answer of Cris is almost perfect and well explained. But it is missing the quotes for the string in the statement.
As the col username will most likely be a varchar of any length.
$query = mysql_query("SELECT * FROM user WHERE username = '{$_SESSION['username']}'");

how to see how many users are online using epoch time?

i am having problem of see who's online and don't have any idea how to see who's online.what i am doing is updating mysql database using time(); whenever user log in or refreshes the page.
Then, lastactivity gets filled with epochtime for eg : 1387806657 or 1287373415.
After that i select the lastactivity from database and use this condition but nothing happens.
<?
$result = mysql_query("SELECT lastactivity FROM users WHERE lastactivity!=0");
while($rahul = mysql_fetch_assoc($result)){
$last = $rahul['lastactivity'];
echo $last;
}
?>
</br>
<?
if ($result < time()-3600)
{
$hello = mysql_num_rows($result);
echo $hello;
}
else
{
echo "ERROR!";
}
?>
You could decide that any acticity in a 30 second interval from now means "online"
$early = time()-30;
$res = mysql_query("SELECT username,lastactivity FROM users WHERE lastactivity > $early") or die( mysql_error() );
while( $row = mysql_fetch_array($res) )
{
echo $row['username'].' is online.<br>';
}
How about going to the source and parsing or watching your Apache log to see which pages are being loaded?

Redirect if user has acces level 2 or higher

So I am making an simple PHP project and I dont have much exprience with PHP.
Maybe you guys can help me out.
I have a database wich stores user crendentials, which looks like this.
id|Username|Password| Mail |Acces|
1 |Josh | ***** |Something#hotmail.com| 1 |
2 |Rick | **0** |Generalpo#hotmail.com| 2 |
And on my php page I want to make it so if the Acces level out of the database is higher then 1 it does a redirect. I am doing it with echo's right know so i don't get redirected all the time. But every time i do this i just get i dont have enough rights. while i am logging in with the Username Josh.
$sql = "SELECT * From login Where Username= "'$_SESSION('username')'"";
while($row = mysql_fetch_row($sql));
if ($row['Acces'] == "1"){
Echo("You have enough rights");
}else{
Echo("You dont have enough rights");
};
Any help is appreciated
You got it partially right, but I would make some changes:
$sql = mysql_query("SELECT * FROM login WHERE Username= '".mysql_real_escape_string($_SESSION['username'])."'");
$sql_fetched = mysql_fetch_assoc($sql);
if ($sql_fetched['Acces'] > 1)
{
echo "You have enough rights and will be redirected automatically.";
header('refresh:3;url=redirect.php');
}
else
{
echo "You dont have enough rights.";
header('refresh:3;url=login.php');
}
$sql = "SELECT * FROM `login` Where `Username`='{$_SESSION['username']}'";
while($row = mysql_fetch_row($sql)) {
if ($row['Acces'] == "1") {
// Change these two headers to the file you want to redirect too
header("Location: http://www.yoursite.com/enoughrights.php");
} else {
header("Location: http://www.yoursite.com/notenough.php");
}
}
$sql = "SELECT * From login Where Username= "'$_SESSION('username')'"";
while($row = mysql_fetch_row($sql));
if ($row['Acces'] == "1"){
header('Location: http://www.example.com/'); /* Redirect browser */
}else{
echo('You dont have enough rights');
};
Change http://www.example.com/ to your desired one.

Send hidden variables from one page to another

I have a Login script that is on my home page for my Login form that is also on my home page. When the user submits the form to Login he/she submits his/her username and password.
The database that the script accesses has the Username, Password, and Email Address stored from the users registration.
Once the user logs in successfully, he/she is redirected to a page that loads their previous "reviews" on the page which are stored within a different table within the same database.
I need to send the email from one table to the query on the redirected page.
Here is the code of my PHP code that processes the Login:
<?php
//If the user has submitted the form
if(isset($_REQUEST['username'])){
//protect the posted value then store them to variables
$username = protect($_POST['username']);
$password = protect($_POST['password']);
//Check if the username or password boxes were not filled in
if(!$username || !$password){
//if not display an error message
echo "<center>You need to fill in a <b>Username</b> and a <b>Password</b>!</center>";
}else{
//if they were continue checking
//select all rows from the table where the username matches the one entered by the user
$res = mysql_query("SELECT * FROM `users` WHERE `username` = '".$username."'");
$num = mysql_num_rows($res);
//check if there was no match
if($num == 0){
//if none, display an error message
echo "<center>The <b>Username</b> you supplied does not exist!</center>";
}else{
//if there was a match continue checking
//select all rows where the username and password match the ones submitted by the user
$res = mysql_query("SELECT * FROM `users` WHERE `username` = '".$username."' AND `password` = '".$password."'");
$num = mysql_num_rows($res);
//check if there was no match
if($num == 0){
//if none display error message
echo "<center>The <b>Password</b> you supplied does not match the one for that username!</center>";
}else{
//if there was continue checking
//split all fields from the correct row into an associative array
$row = mysql_fetch_assoc($res);
//check to see if the user has not activated their account yet
if($row['active'] != 1){
//if not display error message
echo "<center>You have not yet <b>Activated</b> your account!</center>";
}else{
//if they have log them in
//set the login session storing there id - we use this to see if they are logged in or not
$_SESSION['uid'] = $row['id'];
//update the online field to 50 seconds into the future
$time = date('U')+50;
mysql_query("UPDATE `users` SET `online` = '".$time."' WHERE `id` = '".$_SESSION['uid']."'");
//redirect them to the usersonline page
echo 'REDIRECT';
}
}
}
}
exit;
}
?>
Here is the PHP Code that is on the Re-directed to page:
<?php
$con=mysqli_connect("","","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM comments
WHERE email='$_POST[email]' ORDER BY dt");
while($row = mysqli_fetch_array($result))
{
echo $row['dt'] ." " . $row['email'] . " " . $row['body'];
echo "<br>";
echo "<br>";
}
?>
I need to add something to the first code to pick up the email address out of the table it uses to verify the Login information and send it to the second code to receive the "reviews." I have tried googling an answer and came up with nothing. Please help!
Since you have used the $_SESSION array in your code(which maybe is copied from somewhere), you can similarly store the email address in the same array.
$_SESSION['email'] = $row['email'];
In the later page, you'd need to replace $_POST['email'] with $_SESSION['email'].

Categories