get path from file path php

pathinfo

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

pathinfo — Возвращает информацию о пути к файлу

Описание

Подробнее о получении информации о текущем пути, можно почитать в разделе Предопределённые зарезервированные переменные.

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

Если flags не указан, то возвращаются все доступные элементы.

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

Если path содержит больше одного расширения, то PATHINFO_EXTENSION возвращает только последний и PATHINFO_FILENAME удаляет только последнее расширение. (смотрите пример ниже).

Если path не содержит расширения, то не будет возвращён элемент extension (смотрите ниже второй пример).

Если basename параметра path начинается с точки, то все последующие символы интерпретируются как расширение файла ( extension ) и имя файла filename будет пустым (смотрите третий пример).

Примеры

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

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

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

Пример #3 Пример pathinfo() для файла, начинающегося с точки

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

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

User Contributed Notes 37 notes

// result:
// string(11) «lib.inc.php»
// string(15) «/www/htdocs/inc»
?>

pathinfo() is locale aware, so for it to parse a path containing multibyte characters correctly, the matching locale must be set using the setlocale() function.

Reality:
var_dump(pathinfo(‘中国人2016.xls’));
exit();
array(4) < 'dirname' =>string(1) «.» ‘basename’ => string(8) «2016.xls» ‘extension’ => string(3) «xls» ‘filename’ => string(4) «2016» >

Expect(Solve):
setlocale(LC_ALL, ‘zh_CN.UTF-8’);
var_dump(pathinfo(‘中国人2016.xls’));
exit();
array(4) < 'dirname' =>string(1) «.» ‘basename’ => string(17) «中国人2016.xls» ‘extension’ => string(3) «xls» ‘filename’ => string(13) «中国人2016» >

Use this function in place of pathinfo to make it work with UTF-8 encoded file names too

Here is a simple function that gets the extension of a file. Simply using PATHINFO_EXTENSION will yield incorrect results if the path contains a query string with dots in the parameter names (for eg. &x.1=2&y.1=5), so this function eliminates the query string first and subsequently runs PATHINFO_EXTENSION on the clean path/url.

Checked with version 5.5.12:

It works fine with filenames with utf-8 characters, pathinfo will strip them away:

( pathinfo ( «/mnt/files/飛兒樂團光茫.mp3» ));
?>

.. will display:

Array
(
[dirname] => /mnt/files
[basename] => 飛兒樂團光茫.mp3
[extension] => mp3
[filename] => 飛兒樂團光茫
)

Note that this function seems to just perform string operations, and will work even on a non-existent path, e.g.

( pathinfo ( ‘/no/where/file.txt’ ));
?>

which will output:
Array
(
[dirname] => /no/where
[basename] => file.txt
[extension] => txt
[filename] => file
)

if you call pathinfo with a filename in url-style (example.php?with=parameter), make sure you remove the given parameters before, otherwise they will be returned as part of the extension.

unexpected, but longtime (all versions?) consistent, behaviour with trailing slash (Linux):

with Linux I am used, to add a trailing slash,
or just to keep that of the command line completion by [TAB],
to avoid mistyping a path on cp or mv with a same filename instead of a directory

// using php tags here only for syntax highlighting

php > var_dump ( pathinfo ( ‘/home/USER/www.2021-05/’ ));
array( 4 ) <
[ «dirname» ]=> string ( 10 ) «/home/USER»
[ «basename» ]=> string ( 11 ) «www.2021-05»
[ «extension» ]=> string ( 7 ) «2021-05»
[ «filename» ]=> string ( 3 ) «www»
>

When you need to get the file extension to upload a file with a POST method, try this way:

//[‘tmp_name] gets the temporal name of the file (not the real name), which will be used later

//Here is the magic of pathinfo to get the file extension

Источник

realpath

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

realpath — Возвращает канонизированный абсолютный путь к файлу

Описание

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

Несмотря на то, что путь должен быть указан, переданное значение может быть пустой строкой. В этих случаях значение интерпретируется как текущая рабочая директория.

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

realpath() возвращает false при неудаче, например, если файл не существует.

Для регистронезависимых файловых систем, realpath() может нормализовать или не нормализовать регистр символов.

Функция realpath() не будет работать с файлом внутри архива Phar, так как путь может быть не реальным, а виртуальным.

В Windows переходы и символические ссылки на каталоги расширяются только на один уровень.

Замечание: Так как тип integer в PHP является целым числом со знаком, и многие платформы используют 32-х битные целые числа, то некоторые функции файловых систем могут возвращать неожиданные результаты для файлов размером больше 2 Гб.

Примеры

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

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

Пример #2 realpath() на Windows

На Windows realpath() изменит пути стиля Unix на стиль Windows.

echo realpath ( ‘/windows/system32’ ), PHP_EOL ;

echo realpath ( ‘C:\Program Files\\’ ), PHP_EOL ;
?>

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

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

User Contributed Notes 15 notes

As you can so, it also produces Yoda-speak. 🙂

realpath() is just a system/library call to actual realpath() function supported by OS. It does not work on a path as a string, but also resolves symlinks. The resulting path might significantly differs from the input even when absolute path is given. No function in this notes resolves that.

namespace MockingMagician \ Organic \ Helper ;

Источник

basename

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

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

Описание

При передаче строки с путём к файлу или каталогу, данная функция вернёт последний компонент имени из данного пути.

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

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

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

Примеры

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

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

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

User Contributed Notes 30 notes

It’s a shame, that for a 20 years of development we don’t have mb_basename() yet!

There is only one variant that works in my case for my Russian UTF-8 letters:

If your path has a query string appended, and if the query string contains a «/» character, then the suggestions for extracting the filename offered below don’t work.

In such a case, use:

It might be useful to have a version of the function basename working with arrays too.

Here is a quick way of fetching only the filename (without extension) regardless of what suffix the file has.

// your file
$file = ‘image.jpg’ ;

There is a real problem when using this function on *nix servers, since it does not handle Windows paths (using the \ as a separator). Why would this be an issue on *nix servers? What if you need to handle file uploads from MS IE? In fact, the manual section «Handling file uploads» uses basename() in an example, but this will NOT extract the file name from a Windows path such as C:\My Documents\My Name\filename.ext. After much frustrated coding, here is how I handled it (might not be the best, but it works):

If you want the current path where youre file is and not the full path then use this 🙂

www dir: domain.com/temp/2005/january/t1.php

Exmaple for exploding 😉 the filename to an array

A simple way to return the current directory:
$cur_dir = basename(dirname($_SERVER[PHP_SELF]))

since basename always treats a path as a path to a file, e.g.

/var/www/site/foo/ indicates /var/www/site as the path to file
foo

Even though yours is shorter, you can also do:

$ext = end(explode(«.», basename($file

Additional note to Anonymous’s mb_basename() solution: get rid of trailing slashes/backslashes!

echo mb_basename ( «/etc//» ); # «etc»
?>

I got a blank output from this code

suggested earlier by a friend here.

So anybody who wants to get the current directory path can use another technique that I use as

//suppose you’re using this in pageitself.php page

once you have extracted the basename from the full path and want to separate the extension from the file name, the following function will do it efficiently:

On windows systems, filenames are case-insensitive. If you have to make sure the right case is used when you port your application to an unix system, you may use a combination of the following:

//assume the real filename is mytest.JPG:

Because of filename() gets «file.php?var=foo», i use explode in addition to basename like here:

to get the base url of my website

Basename without query string:

Источник

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.

Источник

file_get_contents

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

file_get_contents — Читает содержимое файла в строку

Описание

Использование функции file_get_contents() наиболее предпочтительно в случае необходимости получить содержимое файла целиком, поскольку для улучшения производительности функция использует технику отображения файла в память (memory mapping), если она поддерживается вашей операционной системой.

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

Имя читаемого файла.

Смещение, с которого начнётся чтение оригинального потока. Отрицательное значение смещения будет отсчитываться с конца потока.

Поиск смещения ( offset ) не поддерживается при работе с удалёнными файлами. Попытка поиска смещения на нелокальных файлах может работать при небольших смещениях, но результат будет непредсказуемым, так как функция работает на буферизованном потоке.

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

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

Функция возвращает прочтённые данные или false в случае возникновения ошибки.

Ошибки

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

Примеры

Пример #1 Получить и вывести исходный код домашней страницы сайта

Пример #2 Поиск файлов в include_path

Пример #3 Чтение секции файла

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

Пример #4 Использование потоковых контекстов

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

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

Источник

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

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