如何使用外部 PHP 脚本获取当前的 Joomla 用户

我有几个用于 AJAX 查询的 PHP 脚本,但我希望它们能够在 Joomla 身份验证系统的保护伞下运行.以下安全吗?是否有多余的线条?

I have a couple PHP scripts used for AJAX queries, but I want them to be able to operate under the umbrella of Joomla's authentication system. Is the following safe? Are there any unnecessary lines?

<?php

define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(__FILE__));
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

/* Create the Application */
$mainframe =& JFactory::getApplication('site');

/* Make sure we are logged in at all. */
if (JFactory::getUser()->id == 0)
    die("Access denied: login required.");

?>

test.php:

<?php

include 'joomla-auth.php';

echo 'Logged in as "' . JFactory::getUser()->username . '"';

/* We then proceed to access things only the user
   of that name has access to. */
?>

推荐答案

虽然我在代码中没有看到任何不安全的内容,但最好对标准 Joomla 组件进行 AJAX/JSON 调用.这里有一篇关于如何执行此操作的好文章:http://blog.syncleon.com/2009/05/ajax-ify-your-joomla-website.html 我还在我的书 http://www.packtpub.com/files/learning-joomla-1-5-extension-development-sample-chapter-8-using-javascript-effects.pdf(跳至第 168 页).

While I don't see anything in the code that's unsafe, it's best to make your AJAX/JSON calls to a standard Joomla component. There's a good article on how to do this here: http://blog.syncleon.com/2009/05/ajax-ify-your-joomla-website.html I've also written about JavaScript, Joomla, and asynchronous requests in my book http://www.packtpub.com/files/learning-joomla-1-5-extension-development-sample-chapter-8-using-javascript-effects.pdf (skip down to page 168).

本质上,您所做的是为 AJAX 调用的输出创建一个视图,然后创建一个 view.xml.php(或 view.json.php)文件而不是 view.html.php.当您将 &format=xml 添加到请求 URL 的末尾时,它将从 view.xml.php 而不是 view.html.php 中提取.

Essentially, what you do is create a view for the output of your AJAX call, then create a view.xml.php (or view.json.php) file instead of a view.html.php. When you add &format=xml to the end of your request URL, it will pull from view.xml.php instead of view.html.php.

相关文章