PHP file system functions: opendir, readdir, closedir

PHP provides the programmer with the ability to navigate the siteโ€™s file system to search for files and folders. The use of file system functions for web resources using CMS is especially relevant.

PHP logic and functions for the file system

A file system is represented as a sequence of files and folders located at a specified path. Depending on the operating system, the path is written through a forward or backslash (/ or \).

Folders and files

Calling the PHP function opendir ($ cPath) creates a resource at a given path through which you can sequentially read all the files and folders that are there. The function is not recursive. To view the entire folder structure along a given path, you must write your own algorithm.

Opendir example

In this example, PHP opendir () "opens" the folder at the address "site root" + '/ MphpObj /'. The loop uses the readdir () function, which sequentially reads the entire contents of the folder. Using filetype () in the switch construct allows you to display folder names in one style and file names in another.

The above example includes auxiliary code: the variables $ i and $ j and the โ€œif ($ j) ...โ€ situation switch: after four iterations, the rewinddir () function is applied, and the process starts again.

At the end of the cycle of processing the contents of the specified folder, the closedir () function is applied and the resource created by the opendir () function is closed.

Application practice

Ideally, do not specify names in the path used by the PHP opendir () function. The functionality should be as free as possible in choosing the folder whose contents are of interest. You can start the research process from the root of the site: โ€œ$ _SERVER ['DOCUMENT_ROOT']. '/' โ€And write a recursive view of all folders. This is a popular task, especially for online stores.

Sample tasks for opendir

Sites based on popular management systems force developers and owners to search and change the information they need (photo of goods, data on goods, parsing information and filling the warehouse).

Handmade sites may be interested in storing and reading information outside the database in plain text format.

A programmer can write self-developing code when, depending on operating conditions, it is required to modify * .js, * .css or * .php files.

In all these and many other applications, the PHP functions: opendir, readdir, rewinddir, and closedir allow you to quickly and easily solve the task.

Source: https://habr.com/ru/post/K9482/


All Articles