Checking if specific user is online through php session variable - session

I'm currently trying to display all online users on my webpage using the php session variables. To do this, whenever a user logs in or out, a column in a database gets set to "online" or "offline".. However this doesn't entirely work since the database doesn't get updated when the user closes their browser (and therefor destroys the session).
So is there another way of checking if a certain sessionid is set??
Currently I am setting the session like this:
session_start();
$_SESSION['username']="Example Username";
To check from the current users page if there is a session variable set we can simply use:
if(isset($_SESSION['username']))
{
//username is set
}
But if we need to check if a specific user is online, how do we get for instance an array of all the session variables that have been set? e.g.
//Get all $_SESSION['username'] vars
//loop through array and check for specific $_SESSION
for($i=0; ... )
{
if( $_SESSION['username'][$i] == "User 1" )
{
//do something
}
}
From all that I've read so far, there doesn't seem to be a way to get an array of all sessions on your page..
So is there a better way of doing it, e.g. how do facebook, twitter, etc handle this stuff?
Thanks for your help!

One solution is to store a timestamp in your database in addition to the online/offline flag that records the last time a user accessed any of your website resources. Then you might just consider them offline after 15 minutes or some other constant value.
The other solution is to play with the callbacks here http://php.net/manual/en/function.session-set-save-handler.php where I think you can handle the gc callback and set the offline flag in your database.
If you search on that page for class SessionDB or go here it looks like somebody has implemented some version of this already in a custom class!

you can use a simple update query
for example you have a table users and in that you have a column called status(online/offline)
on your login.php use
<?php
//your user verification code
if(variable that holds your sql query){
$user_status=('UPDATE user SET status= online WHERE email="'your user email selector'")
}
then on the logout do a similar script just change the online value to offline

You could try this:
foreach ($_SESSION as $sessionKey => $sessionValue)
{
if( $sessionKey == 'username' ) && ( $sessionValue == 'User 1' )
{
//do something
}
}

Related

Is it possible to set user parametr in joomla without session?

The default JUser::setParam() method sets parameters only to the session. Is is possible somehow to store parameters not in the session, that they would be always available? I also found in users table field params, which stores some parameters for current user, but don't know how to add data there...
Have you tried to save the object after adding your param?
$user = JFactory::getUser();
$user->setParam($key, $value);
$user->save;
An easy and comfortable approach would be to use the popular Community Builder Extension which lets you define custom user fields in the administrator backend. It has an API to obtain the CB User Object and to write and read those fields which get stored in the DB as opposed to the session. Simple example without knowing your Joomla/CB version (works with Joomla 2.5 and CB 1.8) and the place (site, admin, external) where this should be executed (assuming your parameter is named customParam and the user id is 42):
cbimport( 'cb.field' );
$mosCbUser = CBUser::getUserDataInstance(42);
// read value
$customParameter = $mosCbUser->customParam;
// write value
$mosCbUser->customParam = 'newnew';
$mosCbUser->store();
/* write value to DB directly with optional boolean third parameter
specifing whether to trigger the user update plugins
like onBeforeUserUpdate or onAfterUserUpdate
*/
$mosCbUser->storeDatabaseValue('cb_adresse', 'new address', false);
be sure to be in CB plugin context, if not already the case, include e.g. like
global $_CB_framework, $_CB_database, $ueConfig;
$app = JFactory::getApplication();
include_once( $app->getCfg( 'absolute_path' ) . '/administrator/components/com_comprofiler/plugin.foundation.php' );

Joomla: How to check if another user (not current user) is online

this is probably really simple but I've gone round in circles trying to get it to work. My forte is HTML/CSS rather than PHP.
I have a 3rd party component that I am customising to show when the user who posted the ad is online. So far I have not been able to get it to work.
I have been passing the user ID I get from the component, to the Joomla user object.
$user =& JFactory::getUser($var_from_component);
I have then tried to check whether the guest flag is set, as I understand that it will be zero if the user is logged in but null if the user is not.
if($user->guest==0) {
echo "User is online";
} else {
echo "User is offline";
}
I have also tried with three equals signs as I want check the value is actually set at zero rather than it being null, so basically I have been messing around with variations of this method for too long. If anyone knows a better way to check then please say. I also tried to check the session table for the userid, but I am not that savvy with mySQL queries.
Thanks in advance!
You can query session table to check if user is logged in or not-
$db =& JFactory::getDBO();
$query = 'SELECT COUNT(userid) FROM #__session AS s WHERE s.userid = '.(int)$userid;
$db->setQuery($query);
$loggedin = $db->loadResult();
if($loggedin){
//echo 'User is logged in';
}
try this,
You can check like
$user = &JFactory::getUser($user_id);
//print_r($user);
if(isset($user->guest))
echo "Online";
else
echo "Offline";
Hope this may help you..

Session post link read/notread

i have create a forum script for my website, all working ok but i m blocked on one think, i try to create a session for visited categoryes and posts, so if the post is not read by the user that is logged in, the script display an image "not_read.png" else the display "read.png"
So my code is like this:
$ctid = isset($_REQUEST['ctid']) ? $_REQUEST['ctid'] : '';
if ($action == 'spost'){
$select_posts = "SELECT * FROM forum_posts WHERE cat_id = '$ctid'....
session_set_cookie_params(0);
session_start();
$_SESSION["CAT-$ctid"] = $ctid;
$ses_post = $_SESSION["CAT-$post_id"];
if ($ses_post == $post_id) {
echo "<img src='read.png'>";
}else{
echo "<img src='no_read.png'>";
}
}
is working but when user logout and login again all post show as not read.
Any idea how can i fix this?
Session is only alive during the lifetime of when you open a browser window and navigate to a site till either your code resets the session or the user closes the browser.
So storing your read/unread flag in session is unacceptable if you want it available to a user between different sessions.
Instead you should create a table and store it along with your forum posts that has an entry for the UserId, PostID which would have a row added every time a user viewed a post. Then use this table to decide if it is read (there is a row in the table) or unread (no row matching the userid/postid)

CodeIgniter: storing sessions in DB, how to know who session came from?

I'm thinking of storing CI sessions in the database so I can display how many users are currently online, who specifically is online, etc.
Looking at http://codeigniter.com/user_guide/libraries/sessions.html, am I right in my understanding that information would be stored in the user_data column of the ci_session table? Meaning, maybe I just store the user's id in there?
CodeIgniter will store the data in the table you specify in your config file. By default, it's ci_session. The session information, what is accessible through $_SESSION for instance, is serialized and saved in a column named user_data. That field will not be able to tell you whether or not the session has expired (or in other words, how many people are online).
What you could do instead is use the last_activity column, which is a timestamp of the last time that session was active. You could run a SQL query that selects the count of session_id where the last_activity is less than 2 minutes ago.
SELECT COUNT(`session_id`) AS `active_user_count` FROM `ci_session` WHERE `last_activity` >= DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 2 MINUTE)
With that said, an existing session doesn't necessarily mean that the user is "signed in". If you need to check that they're signed in, you can use a LIKE operator to add a condition to the WHERE statement that checks if a user is signed in. This will depend on what variable name you're using so have a look at your data and see if you can figure it out.
For example:
SELECT COUNT(`session_id`) AS `active_user_count` FROM `ci_session` WHERE `last_activity` >= DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 2 MINUTE) AND `user_data` LIKE '%s:9:"logged_in";b:1;%'
This works! use it
$session = $this->db->get('ci_sessions')->result_array();
foreach ($session as $sessions) {
$sessio = $sessions['last_activity'] + 7200;
echo $sessio . "time";
echo now();
echo "||";
$custom_data = $this->session->_unserialize($sessions['user_data']);
if (is_array($custom_data)) {
foreach ($custom_data as $key => $val) {
$user[$key] = $val;
}
}
}
print_r($user);
exit();`

How do I create, write, and read session data in CakePHP?

can anyone give me an example on how to create Sessions and write data to it. I've seen syntax on how to write data to a session using write command. But how to create a session and retrieve the values in it.
In my application, I have two data, form_id and user_id that needs to be used in all the page requests. So how do I save it as a session variable and use it across the application?
EDIT
function register()
{
$userId=$this->User->registerUser($this->data);
$this->Session->write('User.UserId',$userId);
//echo "session".$this->Session->read('User.UserId');
$this->User->data=$this->data;
if (!$this->User->validates())
{
$this->Flash('Please enter valid inputs','/forms' );
return;
}
$this->Flash('User account created','/forms/homepage/'.$userId);
}
How to use the session variable 'User.UserId' instead of $userId in $this->Flash('User account created','/forms/homepage/'.$userId);
And can I use this variable in all my view files,because in all the page requests I also pass the userId?
EDIT 2
I have 2 controllers,user and form. I write the userid to a session variable in the users_controller. I have a view file called homepage.ctp,whose action is in the forms_controller. Now how can I use the session variable defined in the users_controller in the homepage? Sorry if I am asking silly questions. I went through the cakebook,but my doubts weren't cleared. I'm also trying trial and error method of coding,so please help me.
EDIT 3
I have a session variable 'uid' which is the user id in the home page action of a controller.
$this->Session->write('uid',$this->data['Form']['created_by']);
I need the same variable in the design action method of the same controller.
When I give
$uid=$this->Session->read('uid');
echo "uid: ".$uid;
the value is not echoed.
Can't I use the session variable in the same controller?
The bakery is your best friend:
http://book.cakephp.org/view/398/Methods
All your session read/writes belong in the controller:
$this->Session->write('Person.eyeColor', 'Green');
echo $this->Session->read('Person.eyeColor'); // Green
In cake php you can create session like this
$this->request->session()->write('user_id', 10);
and you can read session value like this
echo $this->request->session()->read('user_id');
Super Simple!
You don't have to write any code to create session, they are already built in. Then you just use the read and write sessions as mentioned above. Also see here for more details:
http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html
Used in Controllers
http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html
Used in Views
cakephp 4 example of session usage in controllers, views and cells
$session = $this->request->getSession();
$session->write('abc', 'apple');
echo $session->read('abc');
In this case it would be:
$this->Flash('User account created','/forms/homepage/'.$this->Session->read('User.UserId'));
and your second question is anwered by Jason Miy (http://api.cakephp.org/class/session-helper). You can simply use this in your view:
$userId = $session->read('User.UserId');
Reading the appropriate cookbook pages slowly and carefully usually helps a lot...
I found out the reason why the uid wasn't being echoed(edit 3 part of the question).
It is due to a silly mistake, had a white space after the end tag ?> in the controller. Now it is working fine.
when I have strange session behavior, and this help me.
MODEL:
function clearAllDBCache() {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$db->_queryCache = array();
}
`
Acess your Helper SessionHelper in lib/Cake/View/Helper/SessionHelper.php and add the method:
public function write($name = null) {
return CakeSession::write($name);
}

Resources