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.
Related
The code below a member and guest counter . The code runs perfectly however when I add a simple column (online) to the table active_members the entire code stops working (apart from the active_guests as this a separate table)
I have looked tirelessly trying to catch anything that may be causing this I have included the table screenshot below . I would to had add new column (online)that is a varchar to the table members_online and then query in the if SESSION below for that new column .
Why does the code stop working , Can somebody possible see the cause or solution?
As soon as i remove the online column is code runs perfect again .
$sqlt2 query below is the line I want to index the new online column .
include('..\db.php');
$con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname);
//declare variables
$guest_timeout = time() -1 * 60;
$member_timeout = time() -1 * 60;
$guest_ip = $_SERVER['REMOTE_ADDR'];
$time = time();
// if the session is set PUTS THE USER IN MEMBERS TABLE
if(isset($_SESSION['CurrentUser'])){
//if user is logged in
$sqlt = mysqli_query($con,"DELETE FROM active_guests WHERE guest_ip='".$guest_ip."'");
**//I WANT TO ADD TO THE ONLINE COLUMN AND REPLACE A SIMPLE STRING INTO ONLINE**
$sqlt2 = mysqli_query($con,"REPLACE INTO active_members VALUES ('".$_SESSION['CurrentUser']."','".$time."')");
$name = $_SESSION['CurrentUser'] ;
}else{
//if user not in a session PUTS THE USER IN GUESTS TABLE
$sqlt3 = mysqli_query($con,"REPLACE INTO active_guests (guest_ip,time_visited)VALUES ('".$guest_ip."','".$time."')");
}
//execute querys
$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");
$sqlt7 = mysqli_query($con,"SELECT username FROM active_members");
$online_guests = mysqli_num_rows($sqlt6);
if(isset($_SESSION['CurrentUser'])){
$sqlt7 = mysqli_query($con,"SELECT username FROM active_members");
if($sqlt7->num_rows){
while($row = $sqlt7->fetch_object())
{
echo '<pre>',$row->username,'</pre>' ;
}
//$result->free();
}
}else{
echo "Login to see members-online list";
}
$online_members = mysqli_num_rows($sqlt7);
?>
// display results
<div class="container">
<p>_________________________</p>
<p>online Guests : <?php echo $online_guests ; ?></p>
<p>online Members : <?php echo $online_members ; ?></p>
</div>
Set column "online"s "Default/Expression" to null, hopefully it'll will work!
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']}'");
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).
Hello there so I am having a little trouble here what I am trying to do is use my code below to show all the users friend requests on the same page, but what is happening is the page is showing only one request at a time then the page has to be refreshed or reloaded for the remaining requests to show up one by one instead off all of them listed down the page any help would be great as I'm trying to learn thank you
<?php
include ('views/header.php');
require_once ('config/config.php');
include ('config/connection.php');
{
global $user_name,$page_owner,$username;
$user_name = trim(strip_tags($_SESSION["user_name"])); //This is the user who logged into the system or logged in session
$page_owner = trim(strip_tags($_SESSION["user_name"])); // This is the owner of the page viewed
$username = mysql_query("select * from request where friend ='".$user_name."'");
$user_id = mysql_query("select user_id from users where user_id = 'user_id'");
//This is the page that checks for Friend Request
$check_request = mysql_query("select * from request where friend = '".$user_name."'"); //First Request receive, first to respond to
if(intval(mysql_num_rows($check_request))==0); //If there is a friend request for the logged in user then show it to the user otherwise do nothing
$get_request_details = mysql_fetch_array($check_request);
//Check friend who sent the request full info from the users table
$check_request_info = mysql_query("select * from `users` where `user_name` = '".mysql_real_escape_string($get_request_details["username"])."'");
//Get friend who sent the request full info from the users table
$get_request_info = mysql_fetch_array($check_request_info);
//Check logged in user full info from the users table
$check_logged_in_user_info = mysql_query("select * from `users` where `user_name` = '".$_SESSION['user_name']."'");
//Get logged in user full info from the users table
$get_logged_in_user_info = mysql_fetch_array($check_logged_in_user_info);
?>
new requests(<?php echo intval(mysql_num_rows($check_request)); ?>)
<div>Hello <?php echo strip_tags($get_logged_in_user_info["user_name"]);?><div>
<div style="font-family:Verdana, Geneva, sans-serif; font-size:11px; line-height:18px;" align="left">Here are your friend requests.</div>
<font style="color:blue;font-family:Verdana, Geneva, sans-serif; font-size:14px;"><?php echo strip_tags($get_request_info["user_name"]); ?> wants to be friends</font><div>
<div>
<div>
<a href="af.php?username=<?php echo $get_request_info["user_name"];
?>"class="square">Accept</a>
Decline
<?php
}
{
//Unknown page realized
}
?>
It's because you only print out one. You never loop through the array containing all friend requests - you echo the first one in the array. If you decline or accept that one, it'll show the next one, and so forth.
See Populate PHP Array from While Loop
The function mysql_fetch_array() only fetches one result row at a time. You want to wrap this in a while loop like so:
while ($get_request_details = mysql_fetch_array($check_request))
{
// do repetitive processing
}
$user_name = mysql_real_escape_string($user_name);
$query ="SELECT user_id FROM users JOIN request ON users.user_id = request.user_id WHERE users.user_id = {$user_name}";
$request = mysql_query($query);
while ( $row = mysql_fetch_assoc($request)){
$results[] = $row;
}
//debug
echo '<pre>';
print_r($results);
and it's a good practice to use LIMIT in your SQL
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'].