When the Apache web server receives an HTTP request from a client browser, it executes the APP_DIR/public/index.php file, also called the entry script.
The entry script is the only PHP file accessible to the outside world. Apache web server directs all HTTP requests to this script (remember the .htaccess file?). Having this single entry script makes the website more secure (comparing with the situation when you allow everyone to access all PHP files of your application).
Although the index.php file is very important, it is surprisingly small (see below):
<?php
use Zend\Mvc\Application;
use Zend\Stdlib\ArrayUtils;
/**
* This makes our life easier when dealing with paths. Everything is relative
* to the application root now.
*/
chdir(dirname(__DIR__));
// Decline static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server') {
$path = realpath(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
if (__FILE__ !== $path && is_file($path)) {
return false;
}
unset($path);
}
// Composer autoloading
include __DIR__ . '/../vendor/autoload.php';
if (! class_exists(Application::class)) {
throw new RuntimeException(
"Unable to load application.\n"
. "- Type `composer install` if you are developing locally.\n"
. "- Type `vagrant ssh -c 'composer install'` if you are using Vagrant.\n"
. "- Type `docker-compose run zf composer install` if you are using Docker.\n"
);
}
// Retrieve configuration
$appConfig = require __DIR__ . '/../config/application.config.php';
if (file_exists(__DIR__ . '/../config/development.config.php')) {
$appConfig = ArrayUtils::merge($appConfig, require __DIR__ . '/../config/development.config.php');
}
// Run the application!
Application::init($appConfig)->run();
Mainly, there are three things done in it.
First, in line 10, current working directory is changed to APP_DIR
.
This makes it simple to define relative file paths in your application.
Next, in line 22, PHP class autoloading is initialized. This allows to easily load any
class either located in Zend Framework library or in your application without the need
for require_once
statement.
And finally, in line 40, an instance of Zend\Mvc\Application
class is created.
The application is initialized with the settings read from application.config.php
configuration file, and, the application is run.