узнать папку файла php
scandir
scandir — Получает список файлов и каталогов, расположенных по указанному пути
Описание
Список параметров
За описанием параметра context обратитесь к разделу Потоки данного руководства.
Возвращаемые значения
Примеры
Пример #1 Простой пример использования функции scandir()
Результатом выполнения данного примера будет что-то подобное:
Примечания
Смотрите также
User Contributed Notes 36 notes
Easy way to get rid of the dots that scandir() picks up in Linux environments:
Here is my 2 cents. I wanted to create an array of my directory structure recursively. I wanted to easely access data in a certain directory using foreach. I came up with the following:
How i solved problem with ‘.’ and ‘..’
I needed to find a way to get the full path of all files in the directory and all subdirectories of a directory.
Here’s my solution: Recursive functions!
Needed something that could return the contents of single or multiple directories, recursively or non-recursively,
for all files or specified file extensions that would be
accessible easily from any scope or script.
scandir() with regexp matching on file name and sorting options based on stat().
name file name
dev device number
ino inode number
mode inode protection mode
nlink number of links
uid userid of owner
gid groupid of owner
rdev device type, if inode device *
size size in bytes
atime time of last access (Unix timestamp)
mtime time of last modification (Unix timestamp)
ctime time of last inode change (Unix timestamp)
blksize blocksize of filesystem IO *
blocks number of blocks allocated
Scandir on steroids:
For when you want to filter your file list, or only want to list so many levels of subdirectories.
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.
PHP Текущее местоположение скрипта, папки, имя файла
В языке PHP есть несколько полезных констант, которые мы можем применять в построении динамического пути к файлу или папке.
Как в PHP узнать полный путь к файлу или папке
Для начала приведу примеры, что вы получите вызвав соответствующие константы:
Мы рассмотрели 2 константы, __FILE__ и __DIR__ для отображения полного пути к текущему файлу и папке (директории). Стоит отметить, что __DIR__ эквивалентен вызову:
dirname — это стандартная функция PHP, которая возвращает родительский каталог. Она применяется как раз для таких ситуаций, когда вам нужно узнать полный путь к файлу без самого файла :). Мне на ум пришла идея, как можно добиться такого же результата (не удивлюсь, если под капотом тоже самое):
Что мы еще можем применить для константы __FILE__? Конечно же отделить путь и получить просто имя файла:
basename — функция возвращает последний элемент из пути, который, как правило, и является именем файла. Раз уж мы решили писать функции заменители, давайте рассмотрим наш URL, как массив, разделенный слешами («/»):
Как видим, последний элемент массива является нашим файлом. Чтобы получить последний элемент массива, не зная его количество, пишем:
Минус 1 потому как отсчет для массивов идет с нуля, но при счете всегда стартует с единицы.
Важно — в некоторых указаниях полного пути вы используете разделители (вышеупомянутые слеши ‘/’). Но, для Windows это «\», для Linux и остальных — «/». Есть такая константа:
Вернет 1 слеш (без кавычек).
Немного закрепим 2 функции, о которых шла речь выше:
str_replace — функция, которая используется для замены в строке. Первый параметр «что ищем», затем «на что меняем» и последний «где ищем», в который мы и передали нашу полную строку.
explode — функция, которая делает из строки массив. Но, чтобы функции понять как разбить строку — ей нужно передать «разделитель», а уже вторым параметром — саму строку.
Как вы заметили, «/home/bitrix/www» — это путь на самом сервере, который можно «вырезать» как раз при помощи str_replace.
Если вам нужно использовать «текущий домен», то получить его при помощи PHP можно несколькими способами. Один из них:
Надеюсь вам эта тема была интересна. Пишите в комментариях как вам формат, и нужен ли он вообще. А то в последнее время только битрикс да битрикс :).
автор: Dmitriy
Занимаюсь веб-разработкой с 2011 года. Посмотреть некоторые из моих работ, а также узнать чуть больше обо мне, вы можете на forwww.ru.
— Создание сайтов на 1С-Битрикс любой сложности
— Вёрстка макетов Figma, Photoshop, Zeplin
— Поддержка проектов на Битриксе
— Разработка нового функционала для сайта
— Парсинг данных
— Выгрузка из файлов в формате XML, YML, XLS, XLSX, CSV, JSON
— Интеграция по API со сторонними сервисами
и многое другое
readdir
(PHP 4, PHP 5, PHP 7, PHP 8)
readdir — Получает элемент каталога по его дескриптору
Описание
Возвращает имя следующего по порядку элемента каталога. Элементы возвращаются в том порядке, в котором они хранятся в файловой системе.
Список параметров
Возвращаемые значения
Возвращает имя элемента каталога в случае успешного выполнения или false в случае возникновения ошибки.
Примеры
Пример #1 Вывести список всех элементов каталога
Смотрите также
User Contributed Notes 29 notes
A function I created to non-recursively get the path of all files and folders including sub-directories of a given folder.
Though I have not tested it completely, it seems to be working.
A variation on listing all the files in a directory recursively. The code illustrates a basic technique : the use of an auxiliary function. It avoids building temporary lists which are merged on the way back. Note that the array which collects the information must be passed by reference.
I wrote several examples on how to use it on my blog at: http://www.pgregg.com/forums/viewtopic.php?tid=73
Ok, the PHP note says my note is too long, so please click on one of the above links to get it.
Looking through the examples, I can’t see any that do a simple check on the value of the directory resource that opendir returns and is subsequently used by readdir.
If opendir returns false, and you simply pass this to the readdir call in the while loop, you will get an infinite loop.
A simple test helps prevent this:
Warning when using readdir() on certain versions of CentOS on NFS-mounted directories:
This is not a bug with PHP’s readdir, but a bug with certain versions of CentOS’s readdir implementation. According to Post #6213 in the CentOS Bugs forum, when using CentOS kernel versions 2.6.18-348 through 2.6.18-348.3.1, invoking readdir on an NFS-mounted directory may not return all the entries. Since PHP’s readdir() uses this library, the issue is manifest in PHP as well.
According to the post, upgrading to version 2.6.18-348.4.1.el5 should solve the issue, though I haven’t tried it.
glob() does NOT seem to suffer from this same vulnerability.
this simple function will index the directories and sub-directories of a given dir
Regarding the warning:
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.
Of course, this means that if you use:
As far as I can tell, the only time this would actually occur is if you encounter an entry of 0.
this appears to be the only string which will evaluate to false.
PHP includes and alternative boolean operators whose precedence is below assignment. This means that an expression of the form
loop through folders and sub folders with option to remove specific files.
## List and Rename all files on recursive directories with «recursive directory name» as template + filename
## Advice: other files in the same directory will result in a warning
## scriptname : Recursive Dir_Renfiles_dirname-filename.php
Get all files on recursive directories in single array.
Array
(
[0] => Array
(
[name] => api
[size] => 0
[perm] => drwxrwxrwx
[type] => dir
[time] => 28 May 2007 01:55:02
)
[1] => Array
(
[name] => classes
[size] => 0
[perm] => drwxrwxrwx
[type] => dir
[time] => 26 May 2007 00:56:44
)
[4] => Array
(
[name] => modules
[size] => 0
[perm] => drwxrwxrwx
[type] => dir
[time] => 28 May 2007 00:47:40
)
[5] => Array
(
[name] => temp
[size] => 0
[perm] => drwxrwxrwx
[type] => dir
[time] => 28 May 2007 04:49:33
)
It should work, but it’ll be better to read section 13.1.3 Cache-control Mechanisms of RFC 2616 available at http://rfc.net/rfc2616.html before you start with confusing proxies on the way from you and the client.
Reading it is the best way to learn how proxies work, what should you do to modify cache-related headers of your documents and what you should never do again. 🙂
And of course not reading RFCs is the best way to never learn how internet works and the best way to behave like Microsoft corp.
Have a nice day!
Jirka Pech
Thought I would include what I wrote to get a random image from a directory.
Below will return an array of file names and folders in directory
A very flexible function to recursively list all files in a directory with the option to perform a custom set of actions on those files and/or include extra information about them in the returned data.
RETURN VALUES:
The function returns an indexed array, one entry for every file. Each entry is an associative array, containing the basic information ‘filename’ (name of file) and ‘dirpath’ (directory component of path to file), and any additional keys you configure. Returns FALSE on failure.
There is a string variable «$path» available, which contains the full path of the current file, relative to the initial «$dir» supplied at function call. This data is also available in it’s constituent parts, «$dir» and «$file». Actions for each file can be constructed on the basis of these variables. The variables «$list», «$handle» and «$recursive» should not be used within your code.
Simply insert you code into the sections indicated by the comments below and your away!
The following example returns filename, filepath, and file modified time (in a human-readable string) for all items, filesize for all files but not directories, and a resource stream for all files with ‘log’ in the filename (but not *.log files).
Here’s a handy function you can use to list the files in the directory you specify, their type (dir or file) and whether they are hidden.
You could modify it to do other things too.
Name Type Invisible (Hidden)?
. Directory Yes
.. Directory Yes
.DS_Store File Yes
.localized File Yes
index.php File No
OOOLS Directory No
QwerpWiki.php File No
/**
* Return the number of files that resides under a directory.
*
* @return integer
* @param string (required) The directory you want to start in
* @param boolean (optional) Recursive counting. Default to FALSE.
* @param integer (optional) Initial value of file count
*/
This function is used to display random image i.e. at header position of a site. It reads the whole directory and then randomly print the image. I think it may be useful for someone.
Find a file or folder within a directory. Say we want will loop n times by all subdirectories of a root directory and find a particular folder or file and know your address.
= ‘../Classes’ ;
$search_parameter = «CachedObjectStorageFactory.php» ;
//if we call the function spider as spider($root);
//will show all the directory content including subdirectories
//if we call the function spider as spider(‘../Classes’, ‘Shared’);
//and will show the address of the directory
Создание сайта на WordPress
Что как и почему в WordPress
Чтение файлов и каталогов в php-сценарии
Путь к файлу
В то время как абсолютный путь к файлу в Windows начинается с имени диска (например, «C:/www/html/file.html»), абсолютный путь к файлу страницы с веб-адресом http://mysite.ru/file1.php, которая находится на Unix-сервере (Apache), имеет вид
Слеш (/) обозначает корневой каталог.
Путь к каталогу, который является корневым для веб-сайта, задается в кофигурации сервера и содержится в системной php-переменной
В данном случае это «»/home/userlogin/public_html/mysite.ru«».
Например, пусть в папке сайта «myplugin» есть файл file2.php и папка «images», в которой находится файл «image1.jpg». Путь к файлу изображения из файла file2.php: «images/image1.jpg».
Чтобы подняться на директорию вверх, нужно написать»../».
Например, в файле file2.php можно указать на файл файл file1.php (в корневой папке сайта) как на файл в родительском каталоге «../file1.php» или в корневом каталоге «/file1.php».
Функции для работы с именами файлов и каталогов
*** Результаты функций, возвращающих информацио о состоянии файлов, кэшируются. Это функции stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype() и fileperms().
Если во время выполнения php-скрипта состояние файла может изменяться, и это нужно проверять, следует очищать кэш. Это делает функция clearstatcache();
Чтение каталога
Чтение каталога без создания дискриптора:
Все файлы с расширением «.txt» из папки «texts» в корневой папке сайта:
Чтение файлов и каталогов в php-сценарии : 1 комментарий
Да есть плагин Wp-editor для этих целей. Весьма функциональный.