-1

I'm trying to get the Joomla User information into my PHP page. You should note that my php code is on the same server, but not within the Joomla installation directory.

Thus, here is my code samples of the important files:

I'm calling a function that returns the Joomla User. The file is called GetUserInfo.php

<?php
Function GetJoomUser() {
    if($_SERVER['SERVER_ADDR'] =='127.0.0.1') {
        $JRoot = $_SERVER['DOCUMENT_ROOT'] . "CBBFL_2014"; 
    } else {
        $JRoot = $_SERVER['DOCUMENT_ROOT'] . "/Joomla33";
    }
    define( '_JEXEC', 1 );
    define('JPATH_BASE', $JRoot );
    define('JPATH_ROOT', $JRoot );
    define( 'DS', DIRECTORY_SEPARATOR );
    $defines = $JRoot . "/includes/defines.php";
    $framework = $JRoot . "/includes/framework.php";
    require_once ($defines);
    require_once ($framework);

    $mainframe = JFactory::getApplication('site');
    $mainframe->initialise();

    $user = JFactory::getUser();
    $JomUser['id'] = $user->id;
    $JomUser['username'] = $user->username;
    // print_r($user);
    return $JomUser;
}
Function GetUserInfo() {
    $JomUser = GetJoomUser();
    // Verify user is found
    $lgDB = 'chasiv_shared';
    include('OpenDB.php');
    $strSQL = "SELECT * FROM chasiv_shared.tbl_users WHERE jom_user ='" . $JomUser['username'] . "';";
    $result = mysqli_query($db, $strSQL);
    if(!$result) { exit("Unable to connect to shared database to identify user."); }
    while($data = mysqli_fetch_assoc($result)) {
        $member['JomUser'] = $JomUser['username'];
        $member['league'] = $data['lg_abbr'];
        $member['team_num'] = $data['lg_team_num'];
        $member['ype_id'] = $data['ype_id'];
        $member['draft_utility'] = $data['draft_utility'];
    }
    return $member;
}

I've edited the below from the original post as HostGator took care of the original error (removed a high level .htaccess which was pointing to php 5.2 instead of php 5.5)

This works fine on my personal test computer. On my webhost, HostGator, it always returns 0 (Guest) regardless of who is logged in.

0
2

I've cleaned up your code a little bit:

function GetJoomUser()
{
    define( '_JEXEC', 1 );

    if($_SERVER['SERVER_ADDR'] == '127.0.0.1') 
    {
        $path = '/CBBFL_2014';
    } 
    else 
    {
        $path = '/Joomla33'
    }

    define( 'JPATH_BASE', realpath(dirname(__FILE__) . $path ));

    require_once ( JPATH_BASE .'/includes/defines.php' );
    require_once ( JPATH_BASE .'/includes/framework.php' );

    $app = JFactory::getApplication('site');
    $app->initialise();

    $user = JFactory::getUser();

    return $user;
}

function GetUserInfo() 
{
    $user = GetJoomUser();

    $db = JFactory::getDbo();

    $query = $db->getQuery(true);
    $query->select($db->quoteName(array('*')))
          ->from($db->quoteName('tbl_users'))
          ->where($db->quoteName('jom_user') . ' = '. $db->quote($user->username));
    $db->setQuery($query);

    $results = $db->loadObjectList();

    foreach($results as $member) 
    {
        $member['JomUser']       = $user->username;
        $member['league']        = $data['lg_abbr'];
        $member['team_num']      = $data['lg_team_num'];
        $member['ype_id']        = $data['ype_id'];
        $member['draft_utility'] = $data['draft_utility'];
    }

    return $member;
}

As you can see now, GetJoomUser returns the whole user object and JPATH_BASE has been properly defined which I think was the reason it wasn't working on your live host. This is assuming the external PHP file is in the root and the Joomla installation is in a sub-directory.

The second function now uses Joomla coding standards for the database query. Before you were using mysql_* which is a NO-GO area. You may need to change the name of the database table in the from->() clause.

IMPORTANT: You are getting the Joomla user object so you must ensure you're actually logged in on the Joomla website, else this won't work.

Let me know is this works

3
  • The php file is in subfolers under the root... root/League/_includes/php/GetUserInfo.php. The Joomla installation is in root/Joomla33. This is the reason I was using the $_SERVER['DOCUMENT_ROOT'] to get the JPATH_BASE & JPATH_ROOT. So your realpath(dirname(FILE))) will return the directory of the php file and not the Joomla installation. Jan 27 '15 at 19:28
  • You should also note that the 2nd function in not connecting to a Joomla database, but instead a separate database for the other part of the site. Thus the reason it was using mysql and not Joomla coding standards. Jan 28 '15 at 21:01
  • OK... So the host fixed the issue returning the error, but now it thinks the Guest in logged in instead of the user (yes, I've assured the user is logged in). Again, this works on the local test machine but not on HostGator. Any thoughts on what php setting or something may be wrong on HostGater to cause this? Feb 18 '15 at 14:04
1

If you are getting 0 and Guest every time on your webserver, I recommend that you step through your conditional statement and subsequent lines of code and ensure that the intended data is being accessed/included/loaded. You will need to show us some more detailed break points if there is any chance of resolving this page.

For the record, I use:

$user = JFactory::getUser();
if (!$user->guest) {...}

to check if a user is a guest or not. I realize this is not a solution for your issue.

As for cleaning up Lodder's clean up of the GetUserInfo() function block, here's my recommendation:

function GetUserInfo()
{
    $user = GetJoomUser();

    $db = JFactory::getDbo();
    $query = $db->getQuery(true)
        ->select($db->quoteName(
            ["jom_user", "lg_abbr", "lg_team_num", "ype_id", "draft_utility"],
            ["JomUser",  "league",  "team_num",    null,     null]
        ))
        ->from($db->quoteName("tbl_users"))  // if tbl_ is the "Joomla prefix", use #__
        ->where($db->quoteName("jom_user") . " = ". $db->quote($user->username));
    $db->setQuery($query);
    return $db->loadAssocList();
}

By making explicit column name and column alias declarations in the SELECT clause, you can assign the output array's keys and values without bothering to loop through the result set. Since the result set is full prepared, just return $db->loadAssocList();

To explain the syntax, the $db->quoteName() call inside of ->select() accepts an array of column names as the first parameter. $db->quoteName() optionally accepts a second parameter which assigns aliases to the value in the first parameter with the same index. What may not be intuitive is the use of null values in the second array. When you don't wish to assign an alias to a column nominated in the first array, use null -- the first array value for that position will be used as the key in the result set subarrays.

The rendered query will look like this:

SELECT `jom_user` AS `JomUser`,`lg_abbr` AS `league`,`lg_team_num` AS `team_num`,`ype_id`,`draft_utility`
FROM `tbl_users`
WHERE `jom_user` = 'somebody'

*one final warning: if you don't have a balanced number of elements in the two arrays within select()'s quoteName() call, the SELECT clause will render empty. Meaning the query will go straight from SELECT to FROM ... on the next line. This is due to conditional requirements in the core code.

Joomla core's quoteName() method:

public function quoteName($name, $as = null)
{
    if (is_string($name))
    {
        $quotedName = $this->quoteNameStr(explode('.', $name));
        $quotedAs = '';
        if (!is_null($as))
        {
            settype($as, 'array');
            $quotedAs .= ' AS ' . $this->quoteNameStr($as);
        }
        return $quotedName . $quotedAs;
    }
    else
    {
        $fin = array();
        if (is_null($as))
        {
            foreach ($name as $str)
            {
                $fin[] = $this->quoteName($str);
            }
        }
        elseif (is_array($name) && (count($name) == count($as)))
        {
            $count = count($name);
            for ($i = 0; $i < $count; $i++)
            {
                $fin[] = $this->quoteName($name[$i], $as[$i]);
            }
        }
        return $fin;
    }
}

Furthermore, if you are not working with indexed arrays, then by definition you will have at least one element which cannot be reached by the $i counter and you will have problems.

Just quietly, I'll add that the extra parentheses in (count($name) == count($as)) are unnecessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.