I have created a custom PHP script which uploads information submitted by a form to a MySQL database. I would like to insert the user id from Joomla of the user who submitted the MySQL data.
To do this I have read that Joomla generates a session cookie while a user is logged into joomla. My hope is to be able to identify the matching cookies and then copy the joomla user id and update the value into the custom mysql database.
Here is what I have so far. It is not functioning properly, but it should give you an idea of the approach to my issue.
<?php
session_start();
//makes connection to databases
include_once "mysql-connect.php";
if (isset($_SESSION['id'])) {
$id = $_SESSION['id']; //I save the id in a session variable
saveUserData($id);
// activeProfile is the name of the cookie used by Joomla/Jomsocial
} elseif (isset($_COOKIE['activeProfile'])) {
$id = $_COOKIE['activeProfile'];
saveUserData($id);
} else {
$return_msg = "not_logged_in";
}
function saveUserData($id) {
// this is where I save the id in a session variable
$_SESSION['id'] = $id;
$myConnJ = mysqli_connect("hostname","username","password","databasename")
or die ("could not connect to joomla");
//query login info from Joomla
$sql = "SELECT * FROM jos_session WHERE id='".$id."'";
$result = mysqli_query($myConnJ, $sql)
or die('ERROR: jos_user query failed for id = $id');
$row = mysqli_fetch_array($result);
echo $row;
// user data I need for charts is saved in session vars
$jom_id = $row['id'];
$_SESSION['jom_id'] = $jom_id;
}
?>
I have tried a variety of echos to get the data to display but nothing is working. Ideally $jom_id would be the user id from the session data that I could insert into the custom database. I think this needs some development on the method of verifying the matched cookies.
One more thing, I was reading up on similar issues and there was the suggestion to use built in Joomla commands to access the Joomla session data. If you have insight onto how I could use these commands, please let me know. Here are some examples of the code:
define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(dirname(__FILE__)));
define( 'DS', DIRECTORY_SEPARATOR );
require_once (JPATH_BASE . DS . 'includes' . DS . 'defines.php');
require_once (JPATH_BASE . DS . 'includes' . DS . 'framework.php');
$mainframe = JFactory::getApplication('site');
As always, thank you for any direction that you can provide. It is very much appreciated.
Maybe I misunderstand what you are asking, for the retrieval of user id is pretty simple in Joomla. In order to get the information from the currently logged user you just acces the
JFactory::getUser()method. No need to bother with sessions:You now have an object containing all the infos you need:
You can get the id like
$id = $user->id;I took the above informations in joomla! wiki: Accessing the current user object
Api documentation of the JUser class: JUser.