Subtracting a path from a document root in PHP

My current root directory of this document (via $ _SERVER ['DOCUMENT_ROOT']):

/var/www/html/clients/app/folder 

I need to create one folder up:

 /var/www/html/clients/app 

How can I do it?

I asked about this in the past: Dynamically finding paths, is there a better way?

However, I have a script that does not work:

  • The executed script is here: root / f1 / f2 / f3 / f4 / f5 / file.php.
  • This script includes another script located here: root / f6 / file2.php

In file2.php, I needed the following code for this:

 $base_path = dirname(realpath("../../../../do_not_remove.txt")); 

If theoretically, based on your location, it should be like this:

 $base_path = dirname(realpath("../do_not_remove.txt")); 

In practice, there is global availability where this data can be transmitted. However, this legacy project does not, so I reuse it when I need it.

Update # 1

Based on the answers, this looks great: realpath($_SERVER['DOCUMENT_ROOT']."/../../");

+4
source share
3 answers

well, you can have - $_SERVER['DOCUMENT_ROOT'] ."/../" - although this does not look too pretty

OR a slightly more convenient way - dirname( $_SERVER['DOCUMENT_ROOT'] ) - think this should work

+4
source
 $path = $_SERVER['DOCUMENT_ROOT']."/../"; 
+3
source

Using explode (), array_pop () and implode ():

 <?php //$path = $_SERVER['DOCUMENT_ROOT']; $path = "/var/www/html/clients/app/folder"; $tmp = explode("/", $path); array_pop($tmp); $path_up = implode('/', $tmp); echo $path_up; //output: /var/www/html/clients/app ?> 
+2
source

Source: https://habr.com/ru/post/1440638/


All Articles