Get Root Directory Path of a PHP Project

Get Root Directory Path of a PHP project

For PHP >= 5.3.0 try

PHP magic constants.

__DIR__

And make your path relative.

For PHP < 5.3.0 try

dirname(__FILE__)

How to get root dir on PHP

Use:

$_SERVER['DOCUMENT_ROOT'];

Get root url of the site in PHP

To return the folder of current php file, use this script.

$url = $_SERVER['REQUEST_URI']; //returns the current URL
$parts = explode('/',$url);
$dir = $_SERVER['SERVER_NAME'];
for ($i = 0; $i < count($parts) - 1; $i++) {
$dir .= $parts[$i] . "/";
}
echo $dir;

PHP how to find application root?

There is $_SERVER['DOCUMENT_ROOT'] that should have the root path to your web server.

Edit: If you look at most major php programs. When using the installer, you usually enter in the full path to the the application folder. The installer will just put that in a config file that is included in the entire application. One option is to use an auto prepend file to set the variable. another option is to just include_once() the config file on every page you need it. Last option I would suggest is to write you application using bootstrapping which is where you funnel all requests through one file (usually with url_rewrite). This allows you to easily set/include config variables in one spot and have them be available throughout all the scripts.

Symfony 4, get the root path of the project from a custom class (not a controller class)

In Symfony AppKernel class is handling the project root directory under method getProjectDir(). To get it in the controller you can do:

$projectRoot = $this->get('kernel')->getProjectDir();

it will return you a project root directory.

If you need the project root directory in one of your classes you have two choices which I will present to you. First is passing AppKernel as dependency:

class Foo 
{
/** KernelInterface $appKernel */
private $appKernel;

public function __construct(KernelInterface $appKernel)
{
$this->appKernel = $appKernel;
}
}

Thanks to Symfony 4 autowiring dependencies it will be autmomaticaly injeted into your class and you could access it by doing:

$this->appKernel->getProjectDir();

But please notice: I don't think it's a good idea, until you have real need and more to do with AppKernel class than getting the project root dir. Specially if you think later on creating about unit tests for your class. You would automatically increase complexity by having a need to create mock of AppKernel for example.

Second option and IMHO better would be to pass only a string with path to directory. You could achieve this by defining a service inside config/services.yaml like this:

services:
(...)
MyNamespace\Foo:
arguments:
- %kernel.project_dir%

and your constructor would look like:

class Foo 
{
/** string $rootPath */
private $rootPath;

public function __construct(string $rootPath)
{
$this->rootPath = $rootPath;
}
}

PHP absolute path to root

Create a constant with absolute path to the root by using define in ShowInfo.php:

define('ROOTPATH', __DIR__);

Or PHP <= 5.3

define('ROOTPATH', dirname(__FILE__));

Now use it:

if (file_exists(ROOTPATH.'/Texts/MyInfo.txt')) {
// ...
}

Or use the DOCUMENT_ROOT defined in $_SERVER:

if (file_exists($_SERVER['DOCUMENT_ROOT'].'/Texts/MyInfo.txt')) {
// ...
}

Composer - how do to get root of project?

PHP has no way of knowing what the "root of the project" is. You could have any number of directories on your disk, with files called vendor/autoload.php in several of them, and only you know what's special about the "project root". So ultimately, the answer is no, there is no way.

However, note that you only need to include the autoloader in files which aren't themselves included or autoloaded. The autoloader is something you load once, as part of the configuration / bootstrapping of your code, and it then loads whatever classes it needs wherever they're referenced.

So the way to limit the mess of different levels is to structure your project carefully. For instance:

  • Route all requests via one or two "routers", such as a single "index.php" file. Use Apache mod_rewrite or the equivalent in Nginx etc to make all URLs actually load this script, and then in the script work out what code to run based on the URL. You can use libraries such as nikic/FastRoute to translate the URLs into functions to call, which will then be autoloaded.
  • Use different PHP files, but all in a reasonably flat directory structure, so that they all have to "climb" the same number of levels to reach the project root.

The same principle applies to use in command-line scripts or any other kind of application: limit or structure the "entry points", because only those need to know where to load the autoloader.

If you already have some kind of config file loaded on every request / script run / unit test / etc, it might be sensible to put the require_once 'vendor/autoload.php'; line in there. Like the configuration, the autoloader is "global state" that you want to just set up once and then forget about.



Related Topics



Leave a reply



Submit