سؤال

I am trying to integrate phpBB3 sessions and data into an external website. I've followed the official resource for this and also read some helpful tips, yet I haven't found a concrete solution to my problem.

Into my site I include a phpbb.php which contains the following code:

<?php
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : '../../forums/';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.' . $phpEx);

// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup();
?>

The root path is configured fine, everything seems to work, and I can use the data on the site with code like this (example):

if ($user->data['user_id'] == ANONYMOUS)
{
    $tpl = new USPTemplate();
    $tpl->load("error_nologin.tpl");
    $tpl->display();
}
else
{
    $tpl = new USPTemplate();
    $tpl->load("review_submit.tpl");
    $tpl->assign("test",'Thanks for logging in, ' . $user->data['username']);
    $tpl->display();
}

This would load different templates with the template system I'm using based on whether or not the user is logged into the forum, and if he is, it also prints his username. All of this works just fine.

The problem however, is when I try to use a function:

function print_login() {
    if ($user->data['user_id'] == ANONYMOUS)
    {
        return "Not currently logged in. [ Log in ]";
    }
    else
    {
        if ( $user->data['user_colour'] != null)
        {
            return "Hello, <b style=\"color: #".$user->data['user_colour']."\">".$user->data['username']."</b>. [ Log out ]";
        }
        else return "Hello, ".$user->data['username'].". [ Log out ]";
    }
}

If I do this, even if the function is on a page which includes the phpbb.php, or even inside the phpbb.php itself, the session will not be recognized and the result will always be:

Hello, . [ Log out ]

Why can't functions I define access the phpBB data?

هل كانت مفيدة؟

المحلول

PHP variables must refer to the global variables, because

<?php
$a = 2;

function test() {
  echo $a;
}
?>

will not work, and

<?php
$a = 2;

function test() {
  global $a;

  echo $a;
}
?>

will work.

In order for your function to work, you have to declare the global variables inside:

function print_login() {
    global $user;

    if ($user->data['user_id'] == ANONYMOUS)
    {
        return "Not currently logged in. [ Log in ]";
    }
...
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top