How to check cookie/session if user is logged in to Joomla?

For Joomla! 1.0 Coding related discussions.
Locked
rebelfighter
Joomla! Apprentice
Joomla! Apprentice
Posts: 24
Joined: Fri Apr 06, 2007 7:13 pm

How to check cookie/session if user is logged in to Joomla?

Post by rebelfighter » Sun Jun 22, 2008 10:38 pm

Hello all the Joomla wizards,

I was wondering if you could help me.

I am writing some PHP pages outside Joomla (version 1.0.12) and would like to password-protect them using Joomla's login system.

The idea is very simple. Just check if Joomla's login cookie or session is available and valid. If so, the PHP page is displayed. If not, user is redirected to Joomla's login page.

So it would look something like this

<?php
if (isset($_SESSION["name"]))
{ echo "Welcome " . $_SESSION["name"] . "!<br />"; }
else
{ header ("location: http://www.mydomain.com/joomla/index.php"); }
?>

I have searched the web and the Joomla 1.0.x developers manual, but could not find what I need to know, namely:
1. which cookie contains the session ID (that could be compared to the session ID value in jos_session db table)
2. how to extract the session ID from the cookie

If I can obtain the session ID, I know how to compare it to the jos_session table.

Could you please advise how to do the above 2 steps (codes please)?

Thanks very much.

RAGEDBULL
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 164
Joined: Wed Jun 21, 2006 2:50 am

Re: How to check cookie/session if user is logged in to Joomla?

Post by RAGEDBULL » Sat Jun 28, 2008 7:26 am

I cannot remember off the top of my head, but if you use your friend print_r you can see what is in the session and other variables like this

Code: Select all

<?php
print_r($_REQUEST);
?>
You could even just throw that in your template and watch the variables change as you log in and out and navigate to see what other information is available to work with for your bridge.

Although, if I recall the session is unique to the site and server serving it, I'm not sure if its maintained when you leave the site, never used session's under such a circumstance.

A better solution would be to throw those PHP pages into Joomla if possible either as a component which dosn't use any of Joomla's functions or inside some wrapper.

hotelag
Joomla! Fledgling
Joomla! Fledgling
Posts: 4
Joined: Tue Jul 15, 2008 8:43 pm

Re: How to check cookie/session if user is logged in to Joomla?

Post by hotelag » Tue Jul 15, 2008 8:48 pm

I am also for looking for a way to verify if the user is logged in. Basically, I am building a component that will use this a lot. Is there not a function you call in Joomla to verify that the user is logged in?

RAGEDBULL
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 164
Joined: Wed Jun 21, 2006 2:50 am

Re: How to check cookie/session if user is logged in to Joomla?

Post by RAGEDBULL » Wed Jul 16, 2008 2:20 am

hotelag wrote: Is there not a function you call in Joomla to verify that the user is logged in?
You do this by testing on the $my variable with a if statement.

I have a tutorial at my website: http://www.webdesignhero.com/index.php? ... &Itemid=13

The original question was to get the information from outside of Joomla.

sudhakargen
Joomla! Apprentice
Joomla! Apprentice
Posts: 5
Joined: Fri Jul 04, 2008 11:25 am

How to check that a user is logged out at any stage

Post by sudhakargen » Thu Jul 17, 2008 6:13 pm

Hi,
I'm using joomla on localhost right now. I wanted an information.
How to check that a user is logged out at any stage in the application.I mean to refer to situations where users doesnt logout.what if he abandons the system and consequently leads to session expiring.How to know this.please tell

RAGEDBULL
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 164
Joined: Wed Jun 21, 2006 2:50 am

Re: How to check cookie/session if user is logged in to Joomla?

Post by RAGEDBULL » Thu Jul 17, 2008 9:48 pm

Hello, first please look at my tutorial.

The logged in status is only in the session variable $my. If $my->id is set, then the user is logged in and has an active session. There is no way to really check if the user is inactive, but still has an active session. In HTTP, it asynchronous communication, so there is no a constant heart beat being recorded by the server, unless you coded something in AJAX possibly, but I think this would be a waste.

Perhaps you are asking something different, but either the user is logged in with an active session or the user does not have an active session, I do not see a difference between an time-out session and logging out on purpose.

User avatar
insupport
Joomla! Apprentice
Joomla! Apprentice
Posts: 42
Joined: Tue Jul 24, 2007 1:33 am

Re: How to check cookie/session if user is logged in to Joomla?

Post by insupport » Fri Oct 03, 2008 8:27 am

Any idea if this is possible in Joomla 1.5.7?

User avatar
trichnosis
Joomla! Explorer
Joomla! Explorer
Posts: 315
Joined: Wed May 17, 2006 4:15 pm

Re: How to check cookie/session if user is logged in to Joomla?

Post by trichnosis » Sun Oct 12, 2008 5:06 pm

Code: Select all

include('configuration.php');
include('includes/joomla.php');
insert that to your external file.

and $my->id will give you the active user id.

function writeUser()
{
global $my;

echo $my->id;
}

User avatar
VideoWhisper
Joomla! Intern
Joomla! Intern
Posts: 54
Joined: Fri Nov 14, 2008 3:32 pm
Contact:

Re: How to check cookie/session if user is logged in to Joomla?

Post by VideoWhisper » Mon Nov 17, 2008 3:17 am

That does not work. It returns "Restricted access.".
Joomla components for Video Conference, Web Video Recorder, P2P Webcam Chat, Video Presentations and Live Streaming: http://www.videowhisper.com + compatible hosting for live streaming and related features.

RAGEDBULL
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 164
Joined: Wed Jun 21, 2006 2:50 am

Re: How to check cookie/session if user is logged in to Joomla?

Post by RAGEDBULL » Sun Feb 01, 2009 6:48 am

In 1.5, you have a user object now.

JUSER
(http://api.joomla.org/Joomla-Framework/User/JUser.html)

You would call a new instance of JUSER, I believe by can create an instance and then access this information, read through the API page.

I just found this tutorial at LeBlanc's website: http://www.jlleblanc.com/joomla/Tutoria ... la!_1%115/ . It's pretty good explanation for anyone who wants a basic solution to the above concepts.

KevinDavis004
Joomla! Apprentice
Joomla! Apprentice
Posts: 32
Joined: Mon Dec 22, 2008 10:35 pm

Re: How to check cookie/session if user is logged in to Joomla?

Post by KevinDavis004 » Tue Feb 10, 2009 10:26 pm

I'm also getting a restricted access error.

Alejo
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 220
Joined: Fri Aug 19, 2005 12:28 pm
Contact:

Re: How to check cookie/session if user is logged in to Joomla?

Post by Alejo » Mon Mar 09, 2009 3:17 pm

To overcome the restricted access message you need to define this constant as shown:

define( '_JEXEC', 1 );

That will let the Joomla scripts run, but I am still not sure the session info will be picked up with the code others have posted here.
https://www.jreviews.com/joomla directory, classifieds, and reviews system for Joomla and WordPress

Alejo
Joomla! Enthusiast
Joomla! Enthusiast
Posts: 220
Joined: Fri Aug 19, 2005 12:28 pm
Contact:

Re: How to check cookie/session if user is logged in to Joomla?

Post by Alejo » Mon Mar 09, 2009 3:43 pm

The solution for this is on another post:

http://forum.joomla.org/viewtopic.php?p ... 3#p1284623

To summarize, this is what I did to make it work.

In my Joomla template index.php I added this:

Code: Select all

// Make session data available outside of Joomla
if(!isset($_COOKIE['jsid'])){
    $user = & JFactory::getUser();        
    $temp_session = $_SESSION; // backup all session data
    session_write_close();
    ini_set("session.save_handler","files"); // set session saved hadler on file
    session_start();
    $_SESSION = (array)$temp_session['__default']['user']; // data that another php file need to know
    session_write_close();
    ini_set("session.save_handler","user"); // put back session saved handler on database
    $jd = new JSessionStorageDatabase();
    $jd->register(); // set required parameters
    session_start(); // restart //
    $_SESSION = $temp_session; // restore last session data
    $e = session_id();
    setcookie("jsid", $e, time()+3600,'/');
}
Outside of Joomla, to read the user session data:

Code: Select all

// Read Joomla session data
if(isset($_COOKIE["jsid"]) && $_COOKIE["jsid"]!=""){
    session_id($_COOKIE["jsid"]);
    session_start();
    $user = $_SESSION;
} else {
    $user = array();  
}
?>   
If the user object is not cast to an array in the template code, then it doesn't work correctly:

$_SESSION = (array)$temp_session['__default']['user'];

It is important to do this and then read the info as:

$user['name']....
https://www.jreviews.com/joomla directory, classifieds, and reviews system for Joomla and WordPress

KevinDavis004
Joomla! Apprentice
Joomla! Apprentice
Posts: 32
Joined: Mon Dec 22, 2008 10:35 pm

Re: How to check cookie/session if user is logged in to Joomla?

Post by KevinDavis004 » Mon Mar 09, 2009 6:34 pm

I see that, however, how about reading session from an external file i.e. an non joomla page?

Thanks!

argenisleon
Joomla! Fledgling
Joomla! Fledgling
Posts: 2
Joined: Thu May 10, 2007 3:57 pm

Re: How to check cookie/session if user is logged in to Joomla?

Post by argenisleon » Mon Jun 15, 2009 3:20 am

Greeting,

The solution seems to work for me but I am getting a empty array in the external php file.

Code: Select all

Array ( [id] => 0 [name] => [username] => [email] => [password] => [password_clear] => [usertype] => [block] => [sendEmail] => 0 [gid] => 0 [registerDate] => [lastvisitDate] => [activation] => [params] => [aid] => 0 [guest] => 1 [_params] => __PHP_Incomplete_Class Object ( [__PHP_Incomplete_Class_Name] => JParameter [_raw] => [_xml] => [_elements] => Array ( ) [_elementPath] => Array ( [0] => /home/snake/public_html/sya/libraries/joomla/html/parameter/element ) [_defaultNameSpace] => _default [_registry] => Array ( [_default] => Array ( [data] => stdClass Object ( ) ) ) [_errors] => Array ( ) ) [_errorMsg] => [_errors] => Array ( ) ) 

Any help would be great.
Thanks in advance.

argenisleon
Joomla! Fledgling
Joomla! Fledgling
Posts: 2
Joined: Thu May 10, 2007 3:57 pm

Re: How to check cookie/session if user is logged in to Joomla?

Post by argenisleon » Mon Jun 15, 2009 5:12 am

Ok I think that I solve the problem. Maybe is something about how session and cookies work that I do not know.

In the moment in which I create the cookie the SESION array is empty. After that I login, but the when i try to get SESSION array from the external php file it is empty.

So I have to create the cookie when a user is login

Code: Select all

$user = & JFactory::getUser();      
 
if ($user->get('id')!=0){
if(!isset($_COOKIE['jsid'])){
    $temp_session = $_SESSION; // backup all session data
    session_write_close();
    ini_set("session.save_handler","files"); // set session saved hadler on file
    session_start();
    $_SESSION = (array)$temp_session['__default']['user']; // data that another php file need to know
    session_write_close();
    ini_set("session.save_handler","user"); // put back session saved handler on database
    $jd = new JSessionStorageDatabase();
    $jd->register(); // set required parameters
    session_start(); // restart //
    $_SESSION = $temp_session; // restore last session data
    $e = session_id();
    setcookie("jsid", $e, time()+3600,'/');
	
}
}
In this way I get what I want. But if I logout from Joomla and I get the SESSION array from the external php file I get the the user data as I was login.

It is a bit confusing, If some one could explain a bit about this would be great. Thanks

myles-e-boy
Joomla! Apprentice
Joomla! Apprentice
Posts: 8
Joined: Wed Jan 21, 2009 8:32 am

Re: How to check cookie/session if user is logged in to Joomla?

Post by myles-e-boy » Wed Jul 22, 2009 3:42 pm

This last code by argenisleon doesn't work for me - any further ideas...

All session data seems to have disappeared. this cookie's there but nothing comes out of the session when I call it like this:
// Read Joomla session data
if(isset($_COOKIE["jsid"]) && $_COOKIE["jsid"]!=""){
session_id($_COOKIE["jsid"]);
session_start();
$user = $_SESSION;
} else {
$user = array();
}
?>

User avatar
brunoazevedo
Joomla! Intern
Joomla! Intern
Posts: 64
Joined: Sun Dec 17, 2006 11:13 am

Re: How to check cookie/session if user is logged in to Joomla?

Post by brunoazevedo » Mon Oct 12, 2009 11:41 pm

Hi,

Please check if this SOLVE:

---------------------------------------------
$user =& JFactory::getUser();

if($user->id)
{
//do user logged in stuff
}
else
{
//do user not logged in stuff
}

------------------------------------------

phatricko1
Joomla! Apprentice
Joomla! Apprentice
Posts: 6
Joined: Tue Jul 15, 2008 3:53 pm

Re: How to check cookie/session if user is logged in to Joomla?

Post by phatricko1 » Mon Jan 25, 2010 7:27 am

brunoazevedo saved the day! That's exactly what I was trying to do! So simple, thank you!

SanderJP
Joomla! Apprentice
Joomla! Apprentice
Posts: 7
Joined: Sat Jan 30, 2010 3:34 pm

Re: How to check cookie/session if user is logged in to Joomla?

Post by SanderJP » Sat Jan 30, 2010 3:36 pm

same here, thanks brunoazevedo, I did use it before but forgot it :)

gurpreet_2109
Joomla! Apprentice
Joomla! Apprentice
Posts: 8
Joined: Wed Feb 03, 2010 7:08 am

Re: How to check cookie/session if user is logged in to Joomla?

Post by gurpreet_2109 » Wed Feb 03, 2010 7:15 am

Hi brunoazevedo, can you plz help me in adding a session check , so that user logged in once won't be able to login on same time. session_id is saved in _session table I need to compare with that, Any help????
Cheers!!
Gurpreet Kaur.
I have not failed. I've just found 10,000 ways that won't work. ;)

gurpreet_2109
Joomla! Apprentice
Joomla! Apprentice
Posts: 8
Joined: Wed Feb 03, 2010 7:08 am

Re: How to check cookie/session if user is logged in to Joomla?

Post by gurpreet_2109 » Tue Feb 16, 2010 12:26 pm

In login function in comprofiler.php(if using cb) add a query to check whether session id is there, then redirect it to error page otherwise allow login.
I hope this helps
Cheers!!
Gurpreet Kaur.
I have not failed. I've just found 10,000 ways that won't work. ;)

fskreuz
Joomla! Fledgling
Joomla! Fledgling
Posts: 1
Joined: Mon Apr 19, 2010 2:10 am

Re: How to check cookie/session if user is logged in to Joomla?

Post by fskreuz » Mon Apr 19, 2010 2:49 am

Hi people, I am new to this forum and just want to help out a little. I read all of the posts here because I was looking for the same thing for my site and found a way for it to work and it may be a bit different but the same. by the way, I use AJAX for this coz i was making an app inside an article page and must find a way to make a check if the user is still logged in for the app to function, if not, restrict the user from further access.

heres what I did step by step:

1.) make a script requesting via ajax to the index.php file of your site (since its the only one editable) along with the parameters like:

Code: Select all

http://www.example.com/index.php?callFunction="somefunction"
2.) add brunoazevedo's code on the initial php code (the one before the doctype area) along with some of what I added:

Code: Select all

include 'customfunctions.php';
$user =& JFactory::getUser();
if($user->id && $_GET['callFunction'])  
{
    //execute the "call" 
    if($_GET['callFunction']=="somefunction")
    {somefunction();}
    else
    {
    //return some value to indicate invalid
    echo "invalid request";
    }
}
else
{
?>
    <!-- all the template HTML until the last bit of code -->
<?
} 
?>
>> customfunctions.php is a php file with your own functions of whatever you want to do when this script tells you that you are logged in. this would typically include responses to return to the ajax funtion (pages for instance, or add to sql table, inputs etc., responses). you may add more files in this manner.

>> $_GET['callFunction'] is some function name passed from the ajax request that has a corresponding function in the customfunctions.php that will get executed when you are logged in.

>> somefunction() is arbitrary, name it however you like, as long as the if statements point to the correct function in the customfunctions.php

all html in the template is encapsulated within the last else block so that when you call the ajax to the index.php file, it wont have to return the whole content of the page, only the part where you need it to tell you that the user is logged in and return what the function should return. this shouldnt affect normal page viewing provided that your variables used in calling in the ajax are not the same name as what joomla uses (ling "category", "section", "Itemid" and all the rest)

use this code for every ajax request because for every request is like loading the index page everytime. its like refreshing your page to check if you are logged out or not. tried this on joomla 1.0 and worked the same way (using another code but similar in structure)

making PHP outside the joomla and using a wrapper to place it inside needs cookies to pass the session to the wrapper which could be a pain since you have to control the session and the cookie. not deleting the cookie may result in unwanted access.

rather if you have the option for javascript, use AJAX to place the PHP content inside the article. that way, it removes the need for a cookie, only the session to worry about, but poses a risk if javascript is not enabled in the user's browser. the app wont run.

Edit: for additional security, you can create random session variables when on the index.php (just before calling the corresponding function) and pass a copy of it to the php upon function call. then when on the php, you compare the session variable and the passed variable before executing any code. if equal then execute, if not or null, discard and do nothing. this way, the php file (get or post method) will not act on its but only under the command of the index.php (from where the session is generated)

ciantic
Joomla! Fledgling
Joomla! Fledgling
Posts: 2
Joined: Mon Jan 19, 2009 8:06 pm

Re: How to check cookie/session if user is logged in to Joom

Post by ciantic » Mon Dec 13, 2010 2:12 pm

There was some pondering how to get the name of the cookie (also 32 char), it happens like this I just found out:

Code: Select all

$session = & JFactory::getSession();
echo $session->getName();
echo $session->getId();
For instance to get SWFUpload to work (on servers where document.cookies is restricted):

Code: Select all

<? ob_start(); ?>
var SWFUpload;
if (typeof(SWFUpload) === "function") {
	SWFUpload.prototype.initSettings = function (oldInitSettings) {
		return function (userSettings) {
			if (typeof(oldInitSettings) === "function") {
				oldInitSettings.call(this, userSettings);
			}
			
			this.injectMyCookies(false);	// The false parameter must be sent since SWFUpload has not initialized at this point
		};
	}(SWFUpload.prototype.initSettings);
	
	// refreshes the post_params and updates SWFUpload.  The sendToFlash parameters is optional and defaults to True
	SWFUpload.prototype.injectMyCookies = function (sendToFlash) {
		if (sendToFlash === undefined) {
			sendToFlash = true;
		}
		sendToFlash = !!sendToFlash;
		
		// Get the post_params object
		var postParams = this.settings.post_params;
		
		postParams["<?=$session->getName()?>"] = "<?=$session->getId()?>";
		postParams["format"] = "raw";
		
		if (sendToFlash) {
			this.setPostParams(postParams);
		}
	};
}
<? $document->addScriptDeclaration(ob_get_clean()); ?>


Locked

Return to “Joomla! 1.0 Coding”