為何大多數的 Joomla! PHP 檔案都以 defined(' JEXEC') 作為開頭...?

From Joomla! Documentation

This page is a translated version of the page Why do most of the Joomla! PHP files start with defined(' JEXEC')? and the translation is 0% complete.

Outdated translations are marked like this.
Other languages:
العربية • ‎Deutsch • ‎English • ‎español • ‎français • ‎Nederlands • ‎中文(台灣)‎

在 Joomla! 中幾乎所有的 PHP 檔案都是由以下宣告聲明開始的:

該聲明宣告會檢查該檔案是否從 Joomla! 內部取出的,並且會保護您的網站,來讓駭客更難以駭入您的網站。

Why do most of the Joomla! PHP files start with defined(' JEXEC')?

它有兩個主要方面的幫助:

The following line is commonly found at the start of Joomla! PHP files:

defined('_JEXEC') or die('Restricted access');

Why?

_JEXEC is a constant that is typically defined in the index.php file at the root of the Joomla! instance and is used to mark a secure entry point into Joomla. The defined or die check makes sure that _JEXEC has been defined in the pathway to get to the file. This is used to ensure that a file that could expose path information because functions, variables or classes aren't defined in that file trip PHP's error reporting and expose a path.
It also prevents accidental injection of variables through a register globals attack that trick the PHP file into thinking it is inside the application when it really isn't.

When?

The check should be added to files that when accessed directly cause a path exposure. For example, the following error occurs when the Backlink System Plugin (/plugins/system/backlink.php file) has had the _JEXEC check disabled:

Fatal error: Call to undefined function jimport() in /Users/pasamio/Sites/workspace/joomla_15/plugins/system/backlink.php on line 18

As is evidenced, the 'jimport' function doesn't exist when the file is directly called so PHP raises an error and exposes the path to the file. Adding the defined or die check to this file will cause a "Restricted access" message to be displayed when the file is accessed.

So the general rule for the JEXEC check is if the PHP file depends on another file to operate properly. Typically if you access a file directly without the JEXEC check and a PHP error is raised (presuming your PHP error reporting is set to show errors by default) about a missing variable, function, object or similar then the file needs to be protected.

Some files don't need to be protected from this check. They might be files with no external dependencies (e.g. a simple class or bit of code) or they might be external files that can operate without being within Joomla!. Examples of this include TinyMCE's GZip'd Javascript generator which is entirely self contained.