php get root dir

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

php get root dir. Смотреть фото php get root dir. Смотреть картинку php get root dir. Картинка про php get root dir. Фото php get root dir

php get root dir. Смотреть фото php get root dir. Смотреть картинку php get root dir. Картинка про php get root dir. Фото php get root dir

Статья, в которой рассмотрим как в php получить путь до корня сайта. Кроме того познакомимся с тем, чем отличается абсолютный путь в PHP и HTML.

Корень (слэш) в HTML и PHP

PHP в отличие от HTML видит файловую систему глубже. В HTML корнем сайта является некоторая директория, которая определяется настройками веб-сервера. Т.е. это определённый каталог в файловой системе, начиная с которого размещаются документы (файлы) этого сайта.

В php слэш ( / ) обозначает корень файловой системы, а не корень сайта.

Чтобы к этому файлу добраться из php необходимо будет проделать более длинный путь. Т.е. сначала добраться до корня сайта (некоторой директории), а потом от него до нужного файла.

Например, на хостинге (в зависимости от хостинга путь до корня сайта может отличаться) путь к файлу будет следующим:

php get root dir. Смотреть фото php get root dir. Смотреть картинку php get root dir. Картинка про php get root dir. Фото php get root dir

Например, путь к файлу сайта, который работает на веб-сервере Apache (сборка Денвер) в операционной системе Windows будет следующим:

php get root dir. Смотреть фото php get root dir. Смотреть картинку php get root dir. Картинка про php get root dir. Фото php get root dir

Чтобы посмотреть путь к корневому каталогу достаточно создать любой php файл и поместить в него следующее содержимое:

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

Источник

dirname

(PHP 4, PHP 5, PHP 7, PHP 8)

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

Описание

Получив строку, содержащую путь к файлу или каталогу, данная функция возвратит родительский каталог данного пути на levels уровней вверх.

В Windows dirname() предполагает текущую установленную кодовую страницу, поэтому для того, чтобы видеть правильное имя каталога с путями многобайтовых символов, необходимо установить соответствующую кодовую страницу. Если path содержит символы, недопустимые для текущей кодовой страницы, поведение dirname() не определено.

В других системах dirname() предполагает, что path закодирован в кодировке, совместимой с ASCII. В противном случае поведение функции не определено.

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

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

На сколько уровней вложенности вверх необходимо пройти.

Должно быть целым числом больше 0.

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

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

Примеры

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

Результатом выполнения данного примера будет что-то подобное:

Смотрите также

User Contributed Notes 29 notes

To get the directory of current included file:

( __FILE__ );
?>

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

Since the paths in the examples given only have two parts (e.g. «/etc/passwd») it is not obvious whether dirname 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 dirname 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 if the path given was a directory then dirname 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

dirname(‘/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 file or directory element off of a path string.

I ran into this when I wrote a site on a url with a path, www.somehost.com/client/somepage.php, where the code above works great, but then wanted to put it on a subdomain, client.somehost.com/somepage.php, where things started breaking.

The best solution would be to create a function that generates absolute URLs and use that throughout the site, but creating a safe_dirname function (and an htaccess rewrite to fix double-slashes just in case) fixed the issue for me:

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

File located locally in: F:\localhost\www\Shaz3e-ResponsiveFramework\S3-CMS\_source

Example 1: dirname($_SERVER[‘PHP_SELF’]); //output: /Shaz3e-ResponsiveFramework/S3-CMS/_source

Getting absolute path of the current script:

( __FILE__ )
?>

Getting webserver relative path of the current script.

( dirname ( __FILE__ ));
?>

If anyone has a better way, get to the constructive critisism!

You can use it to get parent directory:

. include a file relative to file path:

Inside of script.php I needed to know the name of the containing directory. For example, if my script was in ‘/var/www/htdocs/website/somedir/script.php’ i needed to know ‘somedir’ in a unified way.

The solution is:
= basename ( dirname ( __FILE__ ));
?>

Expanding on Anonymous’ comment, this is not necessarily correct. If the user is using a secure protocol, this URL is inaccurate. This will work properly:

A simple way to show the www path to a folder containing a file.

The same function but a bit improved, will use REQUEST_URI, if not available, will use PHP_SELF and if not available will use __FILE__, in this case, the function MUST be in the same file. It should work, both under Windows and *NIX.

The best way to get the absolute path of the folder of the currently parsed PHP script is:

?>

This will result in an absolute unix-style path which works ok also on PHP5 under Windows, where mixing ‘\’ and ‘/’ may give troubles.

[EDIT by danbrown AT php DOT net: Applied author-supplied fix from follow-up note.]

dirname can be used to create self referencing web scripts with the following one liner.

A key problem to hierarchical include trees is that PHP processes include paths relative to the original file, not the current including file.

In some situations (I can’t locate the dependencies) basename and dirname may return incorrect values if parsed string is in UTF-8.

Like, dirname(«glossary/задний-фокус») will return «glossary» and basename(«glossary/задний-фокус») will return «-фокус».

Most mkpath() function I saw listed here seem long and convoluted.
Here’s mine:

If you want to get the parent parent directory of your script, you can use this:

this little function gets the top level public directory

In my mvc based framework i make BASE_PATH and BASE_URL definitions like the following and both work well in the framework without problem.

BASE_PATH is for server side inclusions.
BASE_URL is for client side inclusions (scripts, css files, images etc.)

Code for write permissions check:

If you merely want to find out wether a certain file is located within or underneath a certain directory or not, e.g. for White List validation, the following function might be useful to you:

You can get best root path if you want to call a file from you project paths.

Make sure this define in your www/index.php

or the core file that inside www/ root.

?>

You can call any file any time without any problems

A nice «current directory» function.

function current_dir()
<
$path = dirname($_SERVER[PHP_SELF]);
$position = strrpos($path,’/’) + 1;
print substr($path,$position);
>

I find this usefull for 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 list!

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

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *