Php up from dirname

Получите 2 уровня вверх от имени каталога (__FILE__)

Как я могу вернуть путь из текущего файла, только на 2 каталога вверх?

Итак, если я возвращаю текущий URL-адрес файла theme/includes/functions.php

В настоящее время я использую

7 ответы

PHP 5.2 и ниже

return dirname(dirname(__FILE__)); 

В PHP7 перейдите вверх по дереву каталогов, указав второй аргумент для dirname . Версии до 7 потребуют дальнейшего вложения dirname .

Главное преимущество этого метода над dirname(__FILE__).’/../’; убрать возможную несогласованность DIRECTORY_SEPARATOR? — Патрик

@Patrick Я бы сказал, что главное преимущество этого по сравнению с вашим предложением состоит в том, что мы получаем абсолютный путь к каталогу вместо относительного пути. Кроме того, несоответствия DIRECTORY_SEPARATOR обычно являются крайними случаями, поскольку PHP в большинстве случаев автоматически преобразует разделители стиля * nix в соответствующий разделитель стиля Windows. — Чарльз Спрейберри

что, если вам нужно было подняться на 3+ уровня? Было бы неплохо, если бы второй параметр dirname был $levels , При этом dirname(__FILE__, 3); 🙂 — Geo

@Patrick Другая стратегия, обеспечивающая использование правильного DIRECTORY_SEPARATOR, заключается в том, чтобы обернуть путь в realpath () — Хорхе Орпинель Перес

Даже проще, чем dirname(dirname(__FILE__)); использует __КАТАЛОГ__

который работает с php 5.3 и далее.

[ web root ] / config.php [ admin ] [ profile ] / somefile.php 

Как включить config.php в somefile.php? Вам нужно использовать dirname со структурой 3 каталогов из текущего файла somefile.php.

require_once dirname(dirname(dirname(__FILE__))) . '/config.php'; dirname(dirname(dirname(__FILE__))) . '/config.php'; # 3 directories up to current file 

Поздно к вечеринке, но вы также можете сделать что-то вроде ниже, используя \..\..\ столько раз, сколько необходимо для перехода на более высокий уровень каталогов.

$credentials = require __DIR__ . ‘\..\App\Database\config\file.php’;

$credentials = dirname(__DIR__) . ‘\App\Database\config\file.php’;

Преимущество заключается в том, что он позволяет избежать вложенных имен dirname, например:

Читайте также:  Java для сотовых телефонов

Обратите внимание, что это проверено на сервере IIS — не уверен в сервере Linux, но я не понимаю, почему это не сработает.

Также посмотрите на использование realpath (), например realpath(__DIR__ . ‘/../../’) подняться на два уровня. — Puiu

Как было предложено @geo, здесь расширенная функция dirname, которая принимает второй параметр с глубиной поиска dirname:

/** * Applies dirname() multiple times. * @author Jorge Orpinel * * @param string $path file/directory path to beggin at * @param number $depth number of times to apply dirname(), 2 by default * * @todo validate params */ function dirname2( $path, $depth = 2 )

Примечание: этот @todo может иметь значение.

Единственная проблема заключается в том, что если эта функция находится во внешнем включении (например, util.php), вы не можете использовать ее для включения такого файла: B

Источник

Move up directory levels relative to the current file in PHP

Moving up and down directory levels from the current file in PHP

I often find that simple things are the ones most forgotten or unknown. I’ve recently been helping colleagues learn PHP, and I frequently get asked how to move up and down directory levels in relation to the current file.

I know of two relatively simple ways to do this; one using dirname()
and one using realpath().

We will also be using ‘Magic Constants’ in this post, but handily I’ve explained these a bit here.

Directory levels using dirname()

If you are using PHP 7.0 and above then the best way to navigate from your current directory or file path is to use dirname(). This function will return the parent directory of whatever path we pass to it. In PHP 7 and above we can specify how many levels we would like to move. To use this we first pass the file or directory path as a string, and then specify how many levels we would like to move up from that directory.

Let’s assume that our script is running in /path/to/file/index.php:

$dir = dirname(__DIR__, 2); echo $dir; // Result = "/path"

By using the ‘Magic Constant’ ‘__DIR__’ and specifying a level of 2, we are asking dirname() to return 2 levels up from the parent of ‘__DIR__’. In this case ‘__DIR__’ is ‘/path/to/file’, so 2 levels higher is ‘/path’.

Читайте также:  Display frame in java

Remember: dirname() returns the parent directory, so using ‘dirname(__DIR__)’ will return the parent directory of ‘__DIR__’.

If we use ‘__FILE__’ it is slightly different:

$dir = dirname(__FILE__, 2); echo $dir; // Result = "/path/to"

Because ‘__FILE__’ returns the file in the string, the parent directory is ‘/path/to/file’. By specifying a level of 2 we now move to ‘/path/to’ instead.

Directory levels using realpath()

If you happen to be using an older version of PHP then luckily we can use realpath().

The ‘Magic Constant’ ‘__DIR__’ was added to PHP in 5.3, so for people 5.3 to 5.6 we can move directory levels like this:

Again, assuming that our script is running in /path/to/file/index.php:

$dir = realpath(__DIR__ . '/..'); echo $dir; // Result = "/path/to"

In this example, realpath() resolves the reference ‘/..’ in relation to ‘__DIR__’ and moves us 1 level higher. If we were to use ‘/../..’ then we would move 2 levels higher, and so on.

If we are going back even further than PHP 5.3 then we would have to use realpath(), dirname() and the ‘Magic Constant’ ‘__FILE__’.

Essentially, realpath() won’t accept a file, only a path. This means that we have to remove the ‘index.php’ from our ‘__FILE__’ string. There are a few ways that we could achieve this, one of them is using dirname().

$dir = realpath(dirname(__FILE__) . '/..'); echo $dir; // result = "/path/to"

This example takes the parent directory of ‘__FILE__’ and then resolves ‘/..’ using realpath() to move it 1 level higher.

Источник

PHP How to Go One Level Up on Dirname(_File_)

. but in a web server environment you will probably find that you are already working from current file’s working directory, so you can probably just use:

. to reference the directory above. You can replace __DIR__ with dirname(__FILE__) before PHP 5.3.0.

You should also be aware what __DIR__ and __FILE__ refers to:

The full path and filename of the file. If used inside an include, the name of the included file is returned.

So it may not always point to where you want it to.

Читайте также:  Html files end with

Get folder up one level

. but in a web server environment you will probably find that you are already working from current file’s working directory, so you can probably just use:

. to reference the directory above. You can replace __DIR__ with dirname(__FILE__) before PHP 5.3.0.

You should also be aware what __DIR__ and __FILE__ refers to:

The full path and filename of the file. If used inside an include, the name of the included file is returned.

So it may not always point to where you want it to.

Get 2 levels up from dirname( __FILE__)

PHP 5.2 and lower

return dirname(dirname(__FILE__));

With PHP7 go further up the directory tree by specifying the 2nd argument to dirname . Versions prior to 7 will require further nesting of dirname .

file_get_contents with relative path

$json = file_get_contents(__DIR__ . '/../validate/edit.json');

__DIR__ is a useful magic constant.

For reasons why, see http://yagudaev.com/posts/resolving-php-relative-path-problem/.

When a PHP file includes another PHP file which itself includes yet another file — all being in separate directories — using relative paths to include them may raise a problem.

PHP will often report that it is unable to find the third file, but why?
Well the answer lies in the fact that when including files in PHP the interpreter tries to find the file in the current working directory.

In other words, if you run the script in a directory called A and you include a script that is found in directory B, then the relative path will be resolved relative to A when executing a script found in directory B.

So, if the script inside directory B includes another file that is in a different directory, the path will still be calculated relative to A not relative to B as you might expect.

php how to go two level up on dirname(__FILE__)

Источник

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