Displaying a online user list using PHP - php

Hello everyone so I have partly working code. However I also have issues with it. But let me start off to tell you what I am trying to achieve... On my site I have a login facility which sends all users to a home page once and only if the user is logged in. I would like to display who else is logged in on my page showing there usernames in a list.
My codes current ability...
Okay so i can code it to add the users on joining the site to a database and also then display each user on that database into a div which is great as it displays everyone online...
Where the problem stands...
However, when a user leaves the page there username needs to be deleted from the online user database. In the past I would simply do this with a on window close option in java. But due to Google safari and Firefox no longer supporting this option I am forced to find another way of doing it.
What the code bellow does...
So the code bellow loads an interval so after so much time it will repeat the code within it. The code first adds the user to the database, it then displays the user in a list on the site and then it deletes the user from the database just in case they are to then go offline.
Where the problem stands...
This all being very well for one user, but once a second user gets involved there intervals fall at a different time. So I have deleted the user from the database after it shows the list but then it means the second user displays the database and the first user isn't in it as they are deleted... This also causes a problem should a user go offline half way though the function happening, then it leaves them in the database and doesn't get around to deleting them out of the database.
The following is the java code...
$(document).ready(function() {
var user_name = "<?php print $username ?>";
setInterval(function() {
$.post('onlineusers.php', { name: user_name, action:"joined" });
$.post("onlineusers.php", { action2: "list" }, function(data){
$('#listusers').html(data);
});
$.post("onlineusers.php", { nameleft: user_name, action3:"left" }, function(data){
$('#errorrreport').html(data);
});
}, 5000);
}):
Now there is the PHP document code
//------------User joined page put into database --------
if( $_REQUEST["name"])
{
$user_name = $_REQUEST['name'];
};
if( $_REQUEST["action"])
{
$action = $_REQUEST['action'];
};
if ($action == 'joined') {
user_joined($user_name);
};
//-----------Listing online users within page -------------
if( $_REQUEST["action2"])
{
$action2 = $_REQUEST['action2'];
};
if($action2 == 'list') {
foreach (user_list() as $user){
echo $user . "<br />";
};
};
//------------ User left delete from the database ------------
if( $_REQUEST["nameleft"])
{
$user_nameleft = $_REQUEST['nameleft'];
};
if( $_REQUEST["action3"]){
$action3 = $_REQUEST['action3'];
};
if($action3 == 'left') {
user_left($user_nameleft);
};
//------ Functions what to do... --------
function user_joined($user_name) {
$user_name = mysql_real_escape_string(htmlentities($user_name));
mysql_query("INSERT INTO users (user_name)VALUES('$user_name')") or die("this didn't happen");
}
function user_left($user_nameleft) {
$user_name = mysql_real_escape_string(($user_nameleft));
$query = mysql_query("DELETE FROM users WHERE user_name = '$user_nameleft'")or die("failed to delete from table");
}
function user_list() {
$user_list = array();
$users_query = mysql_query("SELECT user_name FROM users") or die ("Unable to collect userlist");
while ($users_row = mysql_fetch_assoc($users_query)){
$user_list[] = $users_row['user_name'];
}
return $user_list;
}
The above code
Sorry it is slightly messy due to my recoding of it so many times in order to get it to work.
I would appreciate it if anyone could give me any help towards getting this to work. Now if it's not just simple off the code from above I can add the user to the online user database on entrance to the page and get it to list who is online frequently from listing the users on the database.
The real issue and where i am asking for your help with please...
However, if you have any idea on the code for the following that would be great... The user leaving the page is where the problem comes up. I need some method of checking the user is still active and if they are not then deleting them from the database so when the list then refreshes the user is no longer on the list. Such as pinging something until it ends up with no response and deletes the user from the database.
As my current code has problems with multiple users and synchronization of the interval function it needs to take that into account different users will see the list refresh at different times.
P.S. I have also looked at using $SESSION however i am still not sure on how to make this work with checking for offline users and then deleting them from the database this might be a method of doing it.
Thank you, I hope there is enough information to go on.

I've taken a different approach:
JS:
Loop of 5 seconds, AJAX requests onlinenow.php and displays the returned html in the online users box - This is mostly copied and pasted from W3C with the URL changed.
setInterval("getOnline()",5000);
function getOnline()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("onlineNow").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://www.path.com/to/onlinenow.php",true);
xmlhttp.send();
}
PHP:
Takes user/ip/identifier and stores/updates that + unix timestamp in the DB
Returns a list of all rows with unix timestamp in the past 10 minutes
<?php
header('Access-Control-Allow-Origin: *');//Pretty sure this enables cross domain AJAX
$session = $_SERVER['REMOTE_ADDR'];
$time=time();
$time_check=$time-60; //SET TIME 10 Minute
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="pass"; // Mysql password
$db_name="custom"; // Database name
$tbl_name="table"; // Table name
// Connect to server and select databse
mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");
// Check if user is already in the DB
$sql="SELECT * FROM $tbl_name WHERE session='$session'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count=="0"){
//User is not in the DB, lets add them
$sql1="INSERT INTO $tbl_name(session, time, ip)VALUES('$session', '$time', '".$_SERVER['REMOTE_ADDR']."')";
$result1=mysql_query($sql1);
}
//Update this user's entry
else {
//User is in the DB, Update their entry
$sql2="UPDATE $tbl_name SET time='$time' WHERE session = '$session'";
$result2=mysql_query($sql2);
}
//Done updating info, time to get the user list
// if over 10 minute, delete session - Could just get all in past 10 mins instead
$sql4="DELETE FROM $tbl_name WHERE time<$time_check";
$result4=mysql_query($sql4);
//Get total users (Could get a list of names if you preferred and store the info)
$sql3="SELECT * FROM $tbl_name";
$result3=mysql_query($sql3);
$count_user_online=mysql_num_rows($result3);
if ($count_user_online == 1) {
$plur = "";
}
else {
$plur = "s";
}
echo " $count_user_online user".$plur." online now ";
// Close connection
mysql_close();
?>
I've used this logic several times with and without usernames shown (sometimes just a number).
The code, of course, could be improved, but the basic principle is a fairly good solution.

You could try instead of deleting to include a timestamp (server based) when inserting.
Then have the javascript code insert/update every minute or so.
Then your query of who's on is simply which rows have a recent timestamp (like the last 65 seconds)
You'll have to clear out old rows in the table eventually, of course, unless you want a log of everyone who was ever on and when.

Related

How to make a generated code expire after a few times of entering (PHP)?

I have been trying to write a code in PHP that generates a random code, stores it in the database and asks the user to enter it. if the code is entered more than 3 times, the code needs to be expired. this is my code:
<?php
include("ProcessCode.php");
$con = mysqli_connect("localhost","root","") ;
if(mysqli_select_db($con,"login"))
{
echo 'database selected' ;
}
$rand=rand();
echo $rand ;
$sql = "INSERT INTO random (number) VALUES ('$rand') " ;
if(mysqli_query($con,$sql))
{
echo 'inserted' ;
}
?>
$CodeCheck=$_POST['code'];
//Establishing Connection with server
$conn = mysqli_connect("localhost", "root", "");
//Selecting Database
$db = mysqli_select_db($conn, "login");
//sql query to fetch information of registerd user and finds user match.
$query = mysqli_query($conn, "select * from random WHERE number='$CodeCheck'");
$rows = mysqli_num_rows($query);
if (mysqli_num_rows($query) > 0)
{
echo " Code exists already.";
}
if($rows == 1)
{
header("Location: Success.php");
}
else
{
$error = " Code is Invalid";
echo $error;
}
could you please explain how to implement the expiry part?
in your table you could have a field for count. When use login and login is wrong, add + 1 to your count. When user login successfuly, reset the count. If count meet +3, reset the code.
i understand from your question that you need the logic on how to make the random_code expired after inserting from interacted users on your website 3 times ,assuming that , as long as the code is not expired he will be able to do his inserts and you may load it on your page .
i would do that through database queries .
Please follow this instruction listed below
instructions :
while your php page generate the random code , you may store it in database table with a auto reference key , for instance ,
assuming that you have randomly generated a code as below :
"Some random code here"
the above code which was generated by your php page have load it from mysql table called Random_Generated_Code , i would go to edit this table and add new field in it and call it generated_Code_Reference_Key ( could be auto serial number ) to avoid any duplication as well make additional field called Expire_Flag which we are going to use later.
so once your page have loaded the above example code , you should retrieve the generated_Code_Reference_Key along with it and keep it in hidden variable on your page
it should be loaded on the page based on expire_Flag value as a condition
select generated_code from Random_Generated_Code where expire_flag = ""
now once the user try to insert that generated code , in each time he insert it define another table in your database lets call it ( inserted_Codes_by_users) and store in it the username of whoever is doing that on your website as well you have to store the generated_Code_Reference_Key which we are storing in hidden variable as mentioned earlier to indicate which code was used while inserting.
now during page load or any event you want you can find expired code by make select statement from the inserted_Codes_by_users table
select count(generated_Code_Reference_Key) as The_Code_Used_Qty from inserted_Codes_by_users where username = username_of_that_user
so you can get how many times this user have inserted this specific generated_random_Code
retrieve result of the query in a variable and to make sense lets call it The_Code_Used_Qty and make if condition on page load event or any event you like
if The_Code_Used_Qty = 3 then
fire update statement to first table which loaded that random generated code
and update the expire_flag field for that code (Expired) based on reference_key
update Random_Generated_Code set expire_Flag = "expired" where generated_Code_Reference_Key = "generated_Code_Reference_Key" << the one u stored in hidden variable
end if
so now that will get you directly to the point of why we are loading random_generated_code table first time with that condition expire_flag = ""
as it will only retrieve the codes which is not expired .
hopefully this will help you to achieve what you want .
good luck and let me know if you need any help or if you face any confusion while reading my answer.
Good luck .

PHP MySQL Update after Seconds

I want to update a MySQL field after when the site was opened for X Seconds.
I get the Seconds/Time from MySQL and want to update in MySQL when the seconds are over.
I tried
sleep($adddisplaytime);
but then the site waits complete and does not run the things over first
Is there a way to run my update after some seconds when the site is opened?
$query1 = "UPDATE ads SET views = views+1, costs = costs+price WHERE id = '".$adid."'";
Can be in PHP or MySQL
NOTE: This will do what you want, but could be exploited by someone hitting the AJAX endpoint repeatedly, you would want to build in some protections for that.
You will need an additional PHP file, the job of that PHP is to only update the db. You will need to take that update OUT of your page loading script.
Your HTML / JS / PHP for initial load
<script>
setTimeout(function() {
$.ajax('/your/ajax/endpoint.php', {
data: {
'adid': 'your id'
/*
If this is in your PHP file, you can echo the ID straight there.
Not totally recommended, but that's one way An additional /
better way is to add it to a div with a data attribute and
use jQuery to select the data off of there
*/
}
}); // Probably lots more you can do here, but in this case, for simplicity, just sending and that's it
}, 2000); // This will do a 2 second wait
</script>
Your new additional PHP file that is at /your/ajax/endpoint.php
<?php
// THIS FILE DOES THE UPDATE
$adid = $_POST['adid'];
// As mentioned by tadman in his comment.. I would use prepared statements
$query1 = "UPDATE ads SET views = views+1, costs = costs+price WHERE id = ?";
try {
$dbh = new PDO($dsn, $user, $password);
$sth = $dbh->prepare($query1);
$sth->execute(array($adid));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
NOTE:
Again, for security's sake, you really want to consider having your first PHP script generate a unique ID (and store it in the db), that is passed to the page, and having the AJAX send that unique ID with the adid, and if the unique ID you gave is in the database only THEN would you know it's a legitimate request. Remove the unique ID from the database and do the update.
If you want to wait for some seconds after a page is opened and then run the update statement , then write the following codes on the top of the page:-
echo "<script> setTimeout(function(){}, 2000) ; </script>" ;
$query1 = mysqli_query($con, "UPDATE ads SET views = views+1, costs = costs+price WHERE id = '".$adid."'");

Need idea with ajax concept project

i've create a chat in ajax, but i still have some problem that i can't recognize.
When the page is loaded, the php load all the opened chat and relative mex, then there's an addmex ajax function: when the user hits enter it's called passing this.value and the cod_chat. The ajax function send these data to the php, which insert them into the db and add the last mex into the chat. Every X seconds an update function is called, to update the chat.
It all works until it gets to the addmex function: the php works, because it add the mex into the db, but for some reason it refresh the page. Could i use RTMP?
This is the code of the form:
<input type='text' class='chat_input' value='write something' onkeydown='if (event.keyCode == 13){addmex(this.value); this.value='';}'/>
and this is the code of the ajax function (don't worry about the php variables because this function is loaded by echo):
function addmex(mex)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","addmex.php?cod_contatto="+' . $cod_contatto . '+"&mex="+mex,false);
xmlhttp.send();
document.getElementById("messaggi_' . $cod_contatto . '").innerHTML+=xmlhttp.responseText;
}
I set Async as false because it respond slowly, and if i set true works only with some alert that let the server part complete. Any idea?
I've made a mini project script with mysql and this works realy perfect ! You dont need HTTPS for to hidding ajax file. Try this. THIS 100 % WORKS !
MYSQL CODE :
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `ajax_sessions`;
CREATE TABLE `ajax_sessions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`sid` text NOT NULL,
`sip` varchar(18) NOT NULL,
`open` int(1) NOT NULL,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
CREATE FILE NAMED security.php AND INCLUDE IT INTO MAIN PAGE LIKE index.php
INSERT AND SAVE THIS CODE
// INCLUDE YOUR MYSQL CONNECT FILE
require '/engine/config/mysql.php';
// SESSION IP ADDRESS
$sip = $_SERVER['REMOTE_ADDR'];
// COUNT IF TABLE FOR THIS IP ADDRESS EXISTS
$count = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM ajax_sessions WHERE sip = '".$sip."'"));
// COUNT VAR
$count = $count['COUNT(*)'];
// GENERATE RANDOM SESSION ID
$sid = substr(str_shuffle("_-0123456789-_-abcdefghijklmnopqrstuvwxyz-_-ABCDEFGHIJKLMNOPQRSTUVWXYZ-_"), 0, 50);
// YOUR AJAX / XMLHTTP / (LOAD) CALL
echo '
<script>
$("button").click(function() {
$(".container").load("/ajax/request.php?sid='.$sid.'");
});
// CHEC IF CODE WORKS
console.log("Ajax - Session control is activated.");
</script>';
// IF TABLE FOR THIS IP ADDRESS NOT EXISTS INSERT IP,SESSION AND OPEN SESSION.
if($count<1) {mysql_query("INSERT INTO ajax_sessions (sid,sip,open) VALUES ('".$sid."','".$sip."','1')");
} else {
// IF THIS IP ALREADY EXISTS INTO TABLE JUST UPDATE IT AND INSERT SESSION ID.
mysql_query("UPDATE ajax_sessions SET sid = '".$sid."', sip = '".$sip."', open = '1'");
}
PLACE THIS PHP CODE IN TO AJAX FILE
// IF GET sid ( SESSION ID )
if($_GET) {
// CHECK IF SESSION ID IS SET
if(isset($_GET['sid']) && $_GET['sid'] == $_GET['sid'] && !empty($_GET['sid'])) {
// SESSION REMOTE IP ADDRESS
$sip = $_SERVER['REMOTE_ADDR'];
// GET SESSION ID WE GOT
$sid = $_GET['sid'];
// COUNT IF THIS SESSION EXISTS IN MYSQL BASE
$fetch = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM ajax_sessions WHERE sid = '".$sid."' AND sip = '".$sip."' AND open = '1'"));
// COUNT SESSION
if($fetch['COUNT(*)'] == 1) {
// IF SESSION EXISTS CATCH IP ADDRESS AND CLEAR SESSION ID FOR THIS IP AND CLOSE IT, BUT NOT REMOVE
mysql_query("UPDATE ajax_sessions SET sid = NULL, sip = '".$sip."', open = '0'");
} else {
// DIE IF SESSION NOT EXISTS AND DO NOT SHOW CODE
die;
}
// IF IT WORKS OPEN JS CONSOLE LOG WITH F12 FOR GOOGLE CHROME
echo '<script>console.log("Session unseted !")</script>';
}
// AJAX POST CONTENT. IF POST
} else if($_POST) {
echo 'Call request';
}
I KNOW THAT THIS IS HARD TO UNDERSTAND BUT ITS REALY WORKS AND I'M USE IT.
How is your insert field implemented? If it is in a HTML form, it will send the form when you hit enter. So if this is given, you need to prevent the default enter action in order to prevent the page refresh:
Just get the js event (onkeydown), do what you need to do and return false.
EDIT
You may assign the handler in a diffrent way:
Give the input an ID so this will work:
document.getElementById(yourID).onkeydown = function(event) {
if(event.keyCode == 13){addmex(this.value); this.value='';}
return false;
}
EDIT 2
Your first code has a syntax error, it should be:
.... this.value="";}'/></form>
You cant use the same quotes in the inner String: '''' are like 2 strings, while '""' is one string in another.
SOLUTION For those who happen to read this.
The form tag was unnecessary and caused the page to refresh (sometimes preventing default does not work?!).
Finally there was the refreshing via ajax missing. Just do a setInterval() with the function and it should work all fine.
Maybe you can try ArcusNode or Cumulus. I suggest ArcusNode to proceed with. It's an OpenRTMFP protocol.

Determining Account Type from table and Registering Session

Basically what i am trying to do here is to read from the table in my database using the customers login details, then retrieve the record that matches this information. In this table there is a column called "AccountType", this differentiates the average user from a manager, if this column is 1, they are a average user. If this column is 2, they are a manager.
Now im having issues implementing this in my code, below is the snippet of my process script for the login:
<?php
***session_start()
$query = mysql_query("SELECT * FROM accounts WHERE username='$username' and password='$password'", $db) or die ("Query failed with error: ".mysql_error());
$count=#mysql_num_rows($query);
if(***$count == 1)
{
***$user_row = mysql_fetch_array($result)
$userid = $user_row["userid"];
$_SESSION['userid'] = $userid;
$customername = $user_row["customername"];
$_SESSION['customername'] = $customername;
$AccountType = $user_row["accounttype"];
if ($AccountType == 2)
{
$_SESSION['manager'] = $AccountType;
}
Depending on this, when my check login script which every page includes, it will display specific links on the navigation depending what there account type is, if they are user they will have access to normal links, but if they are a manager they have access to admin functions, below is the code snippet for this also:
***session_start();
if (***isset($_SESSION['userid']))
{
$employeeid = $_SESSION['userid'];
$firstname = $_SESSION['customername'];
if (***isset($_SESSION['manager']))
{
$User_Options .='Manager links go here';
}
else
{
$Links .='Normal Links go here';
}
}
Thats just a basic truncated version, but that gives the basis of what im trying to accomplish. I am guessing down to using the while loop its overwriting the session, which i understand, however there will only be one record for the information i am searching. It works to some extent, however even if the AccountType is 1, it displays the options for 2.
Can anyone assist me further in solving this issue? Thankyou!
Use something like this on the login form:
$_SESSION['manager'] = false;
if ($AccountType == 2) {
$_SESSION['manager'] = true;
}
then later:
if ($_SESSION['manager']) {
// display manager-only options
} else {
// display user-only options
}
// Display options for everyone here

Display Notifications

I'm trying to follow the first answer here in order to accomplish my alert feature on my app. Facebook like notifications tracking (DB Design)
but in that example, the user has to open the notifications page to check for new notifications. For me, i need to let user knows that there is a notification (database updated) by displaying an icon like Facebook alerts or something like that.
is there any clear idea about how to do that ?
EDIT
i did something but can't test it coz i don't have my laptop right now.
would you please take a look and let me know if something not OK ?
PHP file
$userID=$_GET["userid"];
//Database connection
$sql = 'SELECT count(*) as count FROM list_notifications WHERE userid ='.$userID;
$qry = pg_query($sql);
$row = pg_fetch_array($qry);
echo $row['count'];
jQuery & JavaScript
var old_count = -1;
setInterval(function() {
$.get("file.php", { userid: "userid" },
function(data){
if (data > old_count) {
alert("the list is updated with: " + data);
//OR
//console.log('the list is updated with:' + data);
old_count = data;
}
}
)},5000); // every 5 seconds
once the user is logged in, the userid must be sent periodically to the php file to check for new notifications. then display them to the user.
for count variable, i made it Increases incrementally with Database trigger.

Categories