1

In CMS or any known php systems the following practice is followed:

In a "main php" file a constant is declared for example in moodle is defined such as MOODLE_INTERNAL and in order to use the database the docs suggest the following (as seen in this piece of documentation):

defined('MOODLE_INTERNAL') || die();
// Rest of code here

As far as I understand this practice is used to check whether the php file is executed "in system".

Whilst frameworks that use PSR-4 autoloading such as symfony, there's not a such requirement and not even is documented as well. Thus I have this burning question:

Why in PSR-4 autoload here's not a such requirement to check whether the php file is executed "in system"?

Dimitrios Desyllas
  • 9,082
  • 15
  • 74
  • 164
  • 1
    It has more to do with MVC. By design all the includes are non-executable on its own. E.g. in psr4 the file which contains class, does not contain any executable code. – Dharman May 03 '19 at 15:32
  • But I can PSR-4 Autload a class without nessesarily use an MVC pattern. – Dimitrios Desyllas May 03 '19 at 15:51

1 Answers1

1

I would argue that this code should be added to files which are only ever meant to be included, but never called themselves. However in PSR-4 the included files never contain executable code, nor should they be directly accessible, that is why this line is no longer necessary. If the file contains only class definition, then executing this file will do nothing.

In the old days you would have code which could span across multiple files and all of it was written in procedural style. If someone accessed this PHP file directly, they could receive errors or worse break your website.

Take a look at how Joomla explains it: Why do most of the Joomla! PHP files start with defined(' JEXEC')?

_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.
(...)
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. - https://docs.joomla.org/JEXEC

Dharman
  • 30,962
  • 25
  • 85
  • 135