PHP.mk документација

dirname

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.dirname.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.dirname.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
dirname

Референца за `function.dirname.php` со подобрена типографија и навигација.

function.dirname.php

dirname

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

dirnameВраќа патека до родителска директориум

= NULL

dirname(string $path, int $levels = 1): string

Даден стринг што содржи патека до датотека или директориум, оваа функција ќе ја врати патеката до родителскиот директориум што е levels од тековната директориум.

Забелешка:

dirname() работи наивно на влезната низа и не е свесен за вистинскиот систем на датотеки, или компоненти на патеката како што се "..".

Безбедност: стандардниот сет на знаци

На Windows, dirname() претпоставува моментално поставена кодна страница, така што за да види правилно име на директориум со патеки со повеќебајтни знаци, мора да биде поставена соодветната кодна страница. Ако path содржи знаци што се невалидни за тековната кодна страница, однесувањето на dirname() е недефинирано.

На други системи, dirname() assumes path да биде кодиран во ASCII компатибилно кодирање. Во спротивно, однесувањето на функцијата е недефинирано.

Параметри

path

Патека.

На Windows, и коса црта (/) и обратна коса црта (\) се користат како знак за разделување на директориуми. Во други средини, тоа е косата црта (/).

levels

Бројот на родителски директориуми за искачување.

Ова мора да биде цел број поголем од 0.

Вратени вредности

Враќа патека до родителски директориум. Ако нема коси црти во path, точка ('.'.') се враќа, што укажува на тековната директориум. Во спротивно, вратениот стринг е path со какви било завршни /component removed.

Безбедност: стандардниот сет на знаци

Бидете внимателни кога ја користите оваа функција во циклус што може да стигне до директориумот на највисоко ниво бидејќи ова може да резултира со бесконечен циклус.

<?php
dirname
('.'); // Will return '.'.
dirname('/'); // Will return `\` on Windows and '/' on *nix systems.
dirname('\\'); // Will return `\` on Windows and '.' on *nix systems.
dirname('C:\\'); // Will return 'C:\' on Windows and '.' on *nix systems.
?>

Примери

Пример #1 dirname() example

<?php
echo dirname("/etc/passwd") . PHP_EOL;
echo
dirname("/etc/") . PHP_EOL;
echo
dirname(".") . PHP_EOL;
echo
dirname("C:\\") . PHP_EOL;
echo
dirname("/usr/local/lib", 2);

Горниот пример ќе прикаже нешто слично на:

/etc
/ (or \ on Windows)
.
C:\
/usr

Види Исто така

  • basename() - Враќа последна компонента на името на патеката
  • pathinfo() - Враќа информации за патеката на датотеката
  • realpath() - Враќа последна компонента на името на патеката

Белешки од корисници 6 белешки

- Враќа канонизирана апсолутна патека
пред 11 години
As of PHP 5.3.0, you can use __DIR__ as a replacement for dirname(__FILE__)
y dot a dot dejong at singular dot of dot alumni dot utwente dot nl
20 години пред
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.

e.g. 

dirname('/usr/local/magic/bin');

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.
tobylewis at mac dot com
пред 23 години
To get the directory of current included file:

<?php
dirname(__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:

<?php
include_once(dirname(__FILE__) . '/database.class.php');
?>
tapken at engter dot de
пред 7 години
Be aware that if you call dirname(__FILE__) on Windows, you may get backslashes. If you then try to use str_replace() or preg_replace() to replace part of the path using forward slashes in your search pattern, there will be no match. You can normalize paths with $path = str_replace('\\',  '/' ,$path) before doing any transformations
bobray at softville dot com
пред 17 години
The dirname function does not usually return a slash on the end, which might encourage you to create links using code like this:
$url = dirname($_SERVER['PHP_SELF']) . '/somepage.php';

However dirname returns a slash if the path you specify is the root, so $url in that case would become '//somepage.php'.  If you put that URL as the action on a form, for example, submitting the form will try to go to http://somepage.php.

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:

<?php
function safe_dirname($path)
{
   $dirname = dirname($path);
   return $dirname == '/' ? '' : $dirname;
}
?>
joe dot naylor at gmail dot com
20 години пред
Attention with this. Dirname likes to mess with the slashes.
On Windows, Apache: 

<?php
echo '$_SERVER[PHP_SELF]: ' . $_SERVER['PHP_SELF'] . '<br />';
echo 'Dirname($_SERVER[PHP_SELF]: ' . dirname($_SERVER['PHP_SELF']) . '<br>';
?>

prints out

$_SERVER[PHP_SELF]: /index.php
Dirname($_SERVER[PHP_SELF]: \
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.