Penggunaan fungsi GETAPPLICATION pada PHP

How we can get the logged in user information and session information from external php script with Joomla-4.x?

Table of Contents

  • Starting a session
  • Displaying or using a session variable
  • Displaying all the session variable.
  • Creating a session variable
  • Checking Session presence
  • Destroying the session
  • Session Duration
  • How do I find my session username?
  • What is PHP session ID?
  • How can I see user details in PHP?
  • How can I access session variable in PHP?

The below code working with Joomla 3.x and doesn't working with Joomla-4.x

define( '_JEXEC', 1 );
define( 'JPATH_BASE', realpath(dirname(__FILE__).'/../..' ));
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
$mainframe = JFactory::getApplication('site');
$mainframe->initialise();
$session = JFactory::getSession();
jimport( 'joomla.application.module.helper' );
 
$session = $session->getId();
$db = JFactory::getDbo();
$user =& JFactory::getUser();
$userid= $user->id;

asked Sep 18, 2021 at 13:54

1

The below code is mostly from Joomla's /includes/app.php but without the last line. The last few lines then get information about the user and the user session.

<?php
define('_JEXEC', 1);
define('JPATH_BASE', __DIR__);
require_once JPATH_BASE . '/includes/defines.php';
require_once JPATH_BASE . '/includes/framework.php';

// Boot the DI container
$container = \Joomla\CMS\Factory::getContainer();

/*
 * Alias the session service keys to the web session service as that is the primary session backend for this application
 *
 * In addition to aliasing "common" service keys, we also create aliases for the PHP classes to ensure autowiring objects
 * is supported.  This includes aliases for aliased class names, and the keys for aliased class names should be considered
 * deprecated to be removed when the class name alias is removed as well.
 */
$container->alias('session.web', 'session.web.site')
    ->alias('session', 'session.web.site')
    ->alias('JSession', 'session.web.site')
    ->alias(\Joomla\CMS\Session\Session::class, 'session.web.site')
    ->alias(\Joomla\Session\Session::class, 'session.web.site')
    ->alias(\Joomla\Session\SessionInterface::class, 'session.web.site');

// Instantiate the application.
$app = $container->get(\Joomla\CMS\Application\SiteApplication::class);

// Set the application as global app
\Joomla\CMS\Factory::$application = $app;

$userInfo = \Joomla\CMS\Factory::getApplication()->getSession()->get('user');
$userSession = \Joomla\CMS\Factory::getApplication()->getSession();

Disclaimer: Most of the information in this post was derived from https://gist.github.com/PhilETaylor/0c36d87da0f2ad231b378b47c54cfb9b

answered Oct 11, 2021 at 11:05

TryHarderTryHarder

2,3304 gold badges20 silver badges46 bronze badges

Sessions are used in PHP in various types of applications to pass data and maintain state of the user. If you are using any membership system where user has to login then after verification we have to keep the login status throughout, so we can maintain the authenticity. To do this we have to use session variables as we will store the userid inside this. Similarly for a shopping cart script we have to store the selected items of the user in session variable and display it to the visitor when required. Sessions are the unique link between the user and the server so all actions of the user can be personalized to the user and handled by the server.

PHP Session variable creating checking and destroying using session_start() using userid and name


We will study how to start a session, how to store variables in a session, how to destroy a session and other related functions for session handling with examples. Here in many scripts we have used sessions and you can use them as an example. Member signup and login script uses them very often. You can download different scripts and read the code to understand how the sessions are used.

Please note that session are handled differently in PHP 5 and above so we will stick to this version only. If you are using PHP 4 then there is small difference in functions ( or syntax ) but the basic concept remains same.

Starting a session

We have verified that user entered login id and password is matching so we will give access by keeping the user id in session variable. Here is the code.
session_start();
$userid="plus2net";
$_SESSION['userid']=$userid; // created session variable
Note that first line session_start(); this line has to be at the top of your page or this function is to be used before we send any data to the browser. The second line actually stores the data to the session variable, this can be any where within the page. The variable $userid stores the user id ( say bigstar ) now the same value is available in our session. Now let us see how to display or use this session variable.

Displaying or using a session variable

As the member has logged, its user id we can display by showing a welcome message. Here is an example.
echo "Welcome $_SESSION[userid]";
Output is here
Welcome plus2net
Note that we must use the function session_start() at the starting of the page ( before sending any output to browser ) to use any session variables.

We can check the existence of session with userid at every page level which are supposed to be used by logged in members.

if(isset($_SESSION['userid']) && !empty($_SESSION['userid'])) {
 echo " session  is available, Welcome $_SESSION[userid] ";
}else{
 echo " No Session , Please Login ";
exit;
}
As you can see we have used isset function to check the presence of session variable storing userid. If the variable does not exist then we are displaying a message asking the user to login and then terminating the script by using exit command. This part of the script you can see in detail at our login and logout script.

Displaying all the session variable.

We can store different data in session variables. In our example we have used only one ( that is $_SESSION[userid] ) but we can store other data also. Let us add name to the session variable like this.

Creating a session variable

$_SESSION['name']="Ronny";
Now we can display all the elements of the session array and see what are the session variables created and what data they store.
while (list ($key, $val) = each ($_SESSION)) { 
echo "$key -> $val <br>"; 
} 
you will get a list like this.
userid -> plus2net 
name -> Ronny

Checking Session presence

Availability of the session can be checked by using isset() and empty functions.
if (isset($_SESSION['userid']&& !empty($_SESSION['userid']))) {
// Welcome message 
}else {
// Ask the user to login
}

Destroying the session

To destroy or delete the sessions we can use these two commands. It is advisable to use these commands in this sequence to destroy remove sessions in PHP.
session_unset();
session_destroy();
Important : Don't forget to give session_start() command at the staring of the page.

Session Duration

If there is no activity or interaction with server for a duration then the server will destroy the session of that particular user. By default the duration is 1440 seconds or 24 minutes. This can be changed at server end by changing the setting inside php.ini file.
session.gc_maxlifetime = 1440
You can test all the above code to learn and understand how the session works by running these sample codes at your system. Open the index.php file and rest you can easily understand.

Assigning unique number to the Session by using session_id


How do I find my session username?

$_SESSION['loggedin'] = $row[$this->pass_column]; $_SESSION['userlevel'] = $row[$this->user_level]; What you have to do is add the $username to the session that is passed into the login function, like below; $_SESSION['username'] = $username; The username will now be stored in the session with the key username.

What is PHP session ID?

session_id() is used to get or set the session id for the current session. The constant SID can also be used to retrieve the current name and session id as a string suitable for adding to URLs. See also Session handling.

How can I see user details in PHP?

The register. php page asks for the desired username, email, and password of the user, and then sends the entered data into the database, once the submit button is clicked. After this, the user is redirected to the index. php page where a welcome message and the username of the logged-in user is displayed.

How can I access session variable in PHP?

Starting a PHP Session It is recommended to put the call to session_start() at the beginning of the page. Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.