Php root dirname file

Php root dirname file Техника

нашел вот такую пачку путей, и получил результат из своей директории:

при этом не важно в какой я папке нахожусь ?

Добавлено через 16 часов 36 минут
решил вопрос следующим образом.
В файлах, которые в папке www тоесть в корневом каталоге сайта, оставляю

По сути выполняется в крон файле всегда

и определяет этот адрес во всех ниже-подключенных файлах

Вы здесь:
Главная — PHP — PHP Скрипты — Определение директорий в PHP

Php root dirname file

При создании сайтов, важной задачей становится работа с файловой системой.
При работе с файловой системой решаются многие проблемы, начиная от определения
корневой директории сайта, до каких-либо файловых операций.

Как получить корневую директорию сайта?

А вот пример получения директории из которой был вызван файл:

Магическая константа FILE содержит абсолютный путь к файлу. dirname — возвращает родительскую директорию файла.

А это другой пример получения директории из которой был вызван скрипт:

Вот так, с помощью простых операции можно получить требуемую информацию.

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (!

Добавляйтесь ко мне в друзья ВКонтакте:Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе:

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

Данная функция возвращает имя каталога, содержащегося в параметре path .

На платформах Windows в качестве разделителей имен директорий используются оба слэша (прямой / и обратный ). В других операционных системах разделителем служит прямой слэш ( / ).

Пример 1. Пример использования функции dirname()

= «/etc/passwd» ;
= ( ); // содержит «/etc»

dirname() изменила своё поведение в PHP 4.3.0. Примеры:

//до PHP 4.3.0
( ‘c:/’ ); // returned ‘.’
//после PHP 4.3.0
( ‘c:/’ ); // returns ‘c:’

dirname() стала правильно обрабатывать двоичные данные начиная с версии PHP 5.0.0

См.также описание функций basename(), pathinfo() и realpath().

User Contributed Notes

jo at durchholz dot org
22-Mar-2006 01:40

OK, I’ll bite 🙂

Things that could be improved are:

1. PHP_SELF isn’t always reliable. (Particularly various (mis-)configured FastCgi installations.) REQUEST_URI is, and it’s reasonably easy to parse. Even better, REQUEST_URI also contains the server name.
2. When concatenating, you don’t need that initial

20-Mar-2006 09:49

I wanted to get just the

folder that the document is in, but not the rest of the url, so here is a simple replacement array. Might be a little more code than neccessary..

borisallan at socialenquiry dot org
05-Mar-2006 02:52

I needed to refer to a directory, one up the tree, so that I had an explicit rather than relative anchor. I couldn’t find a function, so I invented:

which seems to work.
Cheers. BoRiS.

phpcomm-david at tulloh dot id dot au
02-Mar-2006 08:41

This is dirty little trick to allow

() to work with paths with and without files.

= ‘/foo/bar/file’ ;
( ) == ‘/foo/bar’
( . ‘a’ ) == ‘/foo/bar’
= ‘/foo/bar/’ ;
( ) == ‘/foo’
( . ‘a’ ) == ‘/foo/bar’

jay jansheski
28-Feb-2006 05:42

// gets the folder name of the script

function this_folder_name (

ssl at bokehman dot com
22-Sep-2005 12:55

The way this function plays with slashes in windows is a pain so

Дополнительно:  O-So Vanilla Butterscotch Root Beer

renich at woralelandia dot com
10-Aug-2005 09:15

() function
— End Edit —

A nice «

I find this usefull

a lot of stuff! You can maintain a modular site with dir names as modules names. At least I would like PHP guys to add this to the function !

there is anything out there like it, please tell me.

klugg this-is-junk at tlen dot pl
18-Jul-2005 06:14

Attention with this.

likes to mess with the slashes.
On Windows, Apache:

tobylewis at mac dot com
24-Jun-2005 05:52

Since the paths in the examples given only have two parts (e.g. «/etc/passwd») it is not obvious whether

returns the single path element of the parent directory or whether it returns the whole path up to and including the parent directory. From experimentation it appears to be the latter.

returns ‘/usr/local/magic’ and not just ‘magic’

Also it is not immediately obvious that

effectively returns the parent directory of the last item of the path regardless of whether the last item is a directory or a file. (i.e. one might think that the path given was a directory then would return the entire original path since that is a directory name.)

Further the presense of a directory separator at the end of the path does not necessarily indicate that last item of the path is a directory, and so

(‘/usr/local/magic/bin/’); #note final ‘/’

would return the same result as in my example above.

In short this seems to be more of a string manipulation function that strips off the last non-null

or directory element off of a path string.

Holger Thцlking
28-Apr-2005 02:31

23-Feb-2005 08:34

A simple way to have the complete URI of your actual «browsed» page

, as example, W3C css-validation , or any you need it, is:

not AT available DOT com
07-Jan-2005 08:13

There is no distinction between a directory and a file. This is how

() and () work. A directory *is* a file.

Given the path ‘/etc/conf/sample’, there is no way of determining whether ‘sample’ is a

or a directory just by looking at it. Think about that.

temposeb at free dot fr
07-Jun-2004 01:33

Doc : » Given a string containing a path to a

zippy wonder idiot at yahoo dot com
24-Mar-2004 01:40

There are certainly good reasons to use relative includes, though I agree they usually should not be used exclusively. Here’s a couple of common situations:

1) You do not have control over the web server on which you’re developing.

2) You are developing a script or set of scripts

On my own server,

example, I keep all site-wide PHP and JavaScript in /scripts so that I don’t have to worry about where they’re being called from. The files used by my media library, however, are in a scripts subdirectory of the folder the main script runs in. This also makes development easier; the development and production versions simply reside in different folders, allowing them to use different versions of the files without altering the statements.

I am not understanding why everyone seems to want to use relative includes so much.

That will work in any script that is in any single folder on your entire website. No relative paths to mess with. You can just put all your includes in the same folder, and have different names

Дополнительно:  На Ноутбуке Не Работает WiFi - Что Делать, Если Не Подключается Интернет на Windows 7 или 10

them you want.

soywiz at hotmail dot com
02-Jan-2004 05:41

You can use it to get parent directory:

a relative to path:

(dirname(__FILE__) . ‘/path/relative/file_to_include’);

degoede at tomaatnet dot nl
26-Jun-2003 06:58

Easy to have config functionality using

/* UNC path to file, plus trailing slash.
Convert back-slashes to slashes, always, on linux there will be none to replace, but who cares.
Use , as this is the fastest on simple replacements, according to */
= ( «\\», «/», ( __FILE__ ) . «/» ) ;

include_once ( ../../inc.config ) ;
include_once ( get_unc( «include», «inc.some_include» ) ) ;

Now you only need to worry about a relative path once.

philb at gmx dot net
25-May-2003 07:37

// you like put this into an file

function ShowDirModTime (

info at gieson dot com
15-May-2003 05:40

This one will put both the «www» and «file» path into an easy to transport array.



My name is Alex but you can call me WindEagle
my website is
my email is az

// just incase or equals «//»
= («//»,»/»,join(‘/’,).»/»);
= («//»,»/»,join(‘/’,).»/»);

lets say that

Here’s a lil’ code I cooked up to figure out the base directories, as far as filesystem vs. URLs. This is very helpful

, say an image that you want to use (); on, but only have the URL oriented directory. You can then use (); or (); and swap the values out easily!

Note that in order

it to work, you must the pointer ( = &), rather than simply copying ( = ).

andrey at php dot net
14-Jan-2003 06:02

rudecoder at yahoo dot com
11-Jan-2003 11:43

= (, «», ());

Using this method on a

can be used in your HTML to reference other scripts in the same directory.

dave at corecomm dot us
08-Jan-2003 09:20

(‘/rootscript’)==’/’ and (‘/include/includescript’)==’/include’ which have the same number of slashes. This variation is what I’m now using:

This explicitly checks

the root path (/) and uses ‘./’ as the base path we’re in the root folder.
I put this at/near the top of any that calls another. (I used for my own convenience; should work just fine with variables and without testing to see you already did it.)

Note that in both cases (root-folder script and non-root-folder script), BASE_PATH will

a trailing slash. At least with Apache on Darwin (Mac OS X), you can (BASE_PATH.’/myfile’); and the doubled slash won’t cause any problems, giving the same result as (BASE_PATH.’myfile’); .

ludma at pochtamt dot ru
27-Dec-2002 07:35

This function does a correct way to a directory on a server,
it does not recognize only such ways as

Well i had this same problem, includes including files and how to get to overcome the problem of the first

function getPath ()

// get position of file
// save a few nanaseconds, has this been done before,
// has the variable been set ?
// is in root already ?
// there is probably a quicker way to
// the «/»s in the path
// add the number of «../»s required
// declare a variable so you dont have to
// do this again, and return the variable
// just return what it worked out before, function
// only really runs once
//above is at

Дополнительно:  Ноутбук HP не включается — что делать?

improvement i’m sure).

rwf at gpcom dot net
02-Aug-2002 03:08

you want relative includes like C or C++ has, you need to find out where you are in relation to the base path of the server. That is, you are two levels into the «htdocs» directory in apache, then you need to add «../../» to the begining of the to get back to the base directory. That’s simple. What’s NOT so simple is when you have «nested» included files.

Continuing the example above,

The answer to the problem is this: find the number of levels you are currently into the base directory and add as many «../» as you need to the begining of the

filename in EVERY file.

Here’s an example:

Notice that we’re adding the

and the name of the we want together to get the full path. It will look like this: «../../lib»

Notice here that BasePath has already been

so we don’t know or care what BasePath looks like, only that it now allows us to use a relative path to lib2 since it automatically adds the number of «../» needed to get to it from the original example that the server executed. The path here will look like this: «../../lib2»

And now we can easily have lib and lib2 in the same directory, and have lib

lib2 as it’s a relative include.

Pretty simple, no? 🙂

22-May-2002 03:45

you want to know the * System* (not web) Absolute Path (expanding the links) of the script that’s currently being executed, try this:

tapken at engter dot de
30-Apr-2002 11:09

To get the directory of

included :

example, a script called ‘database.init’ which is included from anywhere on the filesystem wants to the script ‘database.class’, which lays in the same directory, you can use:

(__FILE__) . ‘/database.class’);

inconnu0215 at noos dot fr
28-Mar-2002 12:13

To get the highest direcory, a simple method is :

= (dirname());


(PHP 4, PHP 5, PHP 7)

— Возвращает имя родительского каталога из указанного пути



Список параметров

На платформах Windows в качестве разделителей имен директорий
используются оба слеша (прямой / и обратный
). В других операционных системах разделителем
служит прямой слеш (/).

Возвращаемые значения

Возвращает путь к родительской директории. Если в параметре
path не содержится слешей, будет возвращена
точка (‘.’), обозначающая текущую директорию.
В другом случае будет возвращен path
без последнего компонента /component.

Список изменений

Пример #1 Пример использования функции

Функция наивно оперирует исключительно
исходной строкой и не учитывает реальную файловую систему
или компоненты пути типа «..».

учитывает настройки локали, поэтому
для корректной обработки пути с многобайтными символами должна
быть установлена соответствующая локаль с помощью функции

Начиная с версии PHP 4.3.0, функция
вернет слеш или точку там, где ранее возвращалась бы пустая строка.

Посмотрите следующий пример, иллюстрирующий эти изменения:

Вернуться к: Файловая система

Оцените статью
Master Hi-technology
Добавить комментарий