Php root dir path

Get Root Directory Path of a PHP Project

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.

Читайте также:  Opencv python получить цвет пикселя

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', dirname(__FILE__));
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.

Читайте также:  Php массив поменять местами элементы массива

Источник

Find Root Directory Path in PHP

Find Root Directory Path in PHP

  1. Use the __DIR__ Predefined Constant to Find the Path of the Directory of a File in PHP
  2. Use the dirname() Function to Find the Path of the Root Directory of a Project in PHP
  3. Use $_SERVER[‘DOCUMENT_ROOT’] to Find the Document Root Directory of a File in PHP

We will introduce different methods to find the path of the root directory of a PHP project.

Use the __DIR__ Predefined Constant to Find the Path of the Directory of a File in PHP

In PHP, there are predefined constants that can be used to achieve various functionalities. __DIR__ is one magical constant that returns the complete file path of the current file from the root directory. It means it will return the file’s directory. dirname(__FILE__) can also be used for the same purpose.

Suppose we have a project folder which is the root directory of the project. The project folder has the following file path /var/www/HTML/project . Inside the project folder, we have the index.php file and another folder master . Inside the master folder, we have two PHP files: login.php and register.php .

project ├── index.php └── master  ├── login.php  └── register.php 

Suppose we are currently working on login.php . In such a file structure, we can get the directory’s path using the __DIR__ constant in the login.php file. We can use the echo function to print the constant.

Use the dirname() Function to Find the Path of the Root Directory of a Project in PHP

The function dirname(__FILE__) is similar to __DIR__ . We can find the path of the directory of a file using this function. We can also move to the upper levels in the file path using the dirname() function. The first parameter of the function is the path of the file, which is denoted by the __FILE__ constant. The second parameter is an integer which is called levels. We can set the levels to direct the function to level up in the file path. The default value of the level is 1 . As we increase the level, the function will get the file path of one level up. So, we can use this function to find the exact file path of the project’s root directory in PHP.

For example, we can consider the file structure as the first method. Working from the file, login.php , we can use the dirname() function with level 2 and the __FILE__ constant as parameters. Then we can get the exact file path of the working directory. Thus, we can change the levels according to our choice to move upward and downward in the file path. In this way, we can find the path of the root directory of the project in PHP.

php echo dirname(__FILE__,2); ?> 

Use $_SERVER[‘DOCUMENT_ROOT’] to Find the Document Root Directory of a File in PHP

We can use the $_SERVER[] array with the DOCUMENT_ROOT indices to find the document root directory of the currently executing script. It will return the complete path of the document root directory. It is defined in the configuration file in the server. For the file structure above, we can print the $_SERVER[‘DOCUMENT_ROOT’] with the echo function to find the document root directory of the file login.php .

As shown in the output below, we found out the path html is the document root directory of the login.php file. We can see the file path of the root directory as well.

php echo $_SERVER['DOCUMENT_ROOT']; ?> 

Источник

Get Root Directory Path of a PHP project?

In order to get the root directory path, you can use _DIR_ or dirname().

The second syntax is as follows−

Both the above syntaxes will return the same result.

Example

Output

AmitDiwan

  • Related Articles
  • Get all subdirectories of a given directory in PHP
  • C# Program to get the name of root directory
  • How to get root directory information in android?
  • PHP – How to get or set the path of a domain?
  • How to get file name from a path in PHP?
  • How to get full path of current file’s directory in Python?
  • Get the absolute path for the directory or file in Java
  • Find last Directory or file from a given path
  • How to Zip a directory in PHP?
  • Specify a path for a file or a directory in Java
  • How to extract a part of the file path (a directory) in Python?
  • PHP: Unlink All Files Within A Directory, and then Deleting That Directory
  • Java Program to get the File object with the absolute path for the directory or file
  • How to create a directory in project folder using Java?
  • Program for longest common directory path in Python

Annual Membership

Enjoy unlimited access on 5500+ Hand Picked Quality Video Courses

Training for a Team

Affordable solution to train a team and make them project ready.

Tutorials PointTutorials Point

  • About us
  • Refund Policy
  • Terms of use
  • Privacy Policy
  • FAQ’s
  • Contact

Copyright © Tutorials Point (India) Private Limited. All Rights Reserved.

We make use of First and third party cookies to improve our user experience. By using this website, you agree with our Cookies Policy. Agree Learn more

Источник

Оцените статью