Work with files. in php

Lecture




Work with files includes 3 stages.
-Open file;
-Processing (read, write);
-Close the file.

The file is opened by the fopen () function. It needs to pass two parameters: the first is the file name (string), the second is the mode (also a string). Returns a function value of type Resource. In the future, it will be used by other functions that work with files.
If the file is in the current directory, then it is enough to specify only its name (without path). If he is in a different place, you need to specify the hollow path. To change the current directory, use the chdir () function. She needs to give the name of the directory that we want to make current. If the change directory fails, the function returns false.
To find out which directory is currently in use, use getcwd () .
You can learn about all modes in the description of the function, and we will get acquainted with the rest in this chapter.

File processing usually involves reading and / or writing. Let's look at a few functions that read a file.
fgets () . The first parameter is a pointer to the resource. The one that fopen () returned to us. The second parameter, optional, is the number of bytes to read. The function reads the specified number of bytes, or less, if it meets the end of the line or the end of the file earlier. It returns the read string.
file_get_contents () takes the file name and returns its contents in a single line.
file () takes the file name and returns its contents as an array of strings.
When using the last two functions, it is not necessary to open the file with the fopen () function. They will do everything themselves.
The following functions are used to write to the file:
fputs () . The first parameter is a pointer to a resource, the second is a string that we write.
file_put_contents () accepts a string — the name of the file and the string to be written.

The fclose () function closes the file . She needs to pass a pointer to the resource.
Let's look at an example of the effect of these functions. Suppose that numbers are stored in the f1.txt file in the / usr / tmp directory. One per line. We need to count this number, increase it and write to the file f2.txt.

<?PHP
chdir('/usr/tmp');
$src = fopen('f1.txt', 'r'); // 'r' указывает функции открыть файл для чтения
$dst = fopen('f2.txt', 'w'); // 'w' указывает функции открыть файл для записи
while ( !feof($src) ) {
$line = fgets($src, 16);
$line++;
fputs($dst, $line);
}
fclose($dst);
fclose($src);
?>

Here you saw a new function feof () which returns true if after the next operation the end of the file is reached.
Directory functions.
We have just learned two functions of working with directories (by the way, which ones?) But, as you can guess, there are not two of them.
So, like the file, you need to open the directory, and close it at the end of the work. The opendir ($ path) and closedir ($ res) functions do this.
The first takes a string — the path to the directory and returns a directory handle (or false if it could not be opened); the second takes the same handle and returns nothing.

Retreat a little. There is also a scandir ($ path) function . It takes a directory path and returns as an array a list of all directory entries. Open the folder with the opendir () function in this case is not necessary.

Also, it turns out, PHP has a built-in class for working with directories. It is called dir . It contains a path, a descriptor, and methods for reading, closing, and resetting a descriptor. How to use it, you will understand when learn OOP.

So ... back to our readdir (). You got the name of the next catalog item. What to do with him now? You can, for example, display, write to a file, you can still think of something.
For example, you can find out what this item is (another folder, file, link). for this there are appropriate functions. The is_dir ($ path) function takes a string (the path to the element with its name) and returns true if it is a folder, otherwise false. Similarly work   is_file ($ path) and is_link ($ path) . You can also determine the type of element can be a function filetype ($ filename) , passing it the file name. The function returns a string with one of the following values: fifo, char, dir, block, link, file, or unknown.

So what can we do with the directory after we open it?
For example, you can find out what is in it. The readdir ($ res) function takes a directory handle obtained after using opendir () and returns the name of the next directory element. Under the directory elements refers to the folder or file that is located in it. If you call this function after getting the name of the last item in the directory, it returns false. Having determined what this element is, we can do something else with it. If the file is opened and processed, if the directory is a list of its elements and not only.

There is also a function clearstatcache () . It clears the file status cache. If you make any changes in the files with your own script, and then work based on these changes, then call this function after the changes. Otherwise, your changes may not be detected. For example, you write to a file until its size reaches, say, 2MB. And check the size after each entry. And despite the fact that the file has already grown to 2GB, php still sees its original size. But if you are clearstatcache (), then everything will be fine.

Let's look at a small example: open the directory / usr / home / mydir and see what it is.

<?PHP
$dir_hndl = opendir('/usr/home/mydir');
while (false !== ($name = readdir($dir_hndl))) {
if ($name == '..') {
echo 'Parent directory<br>';
continue;
} elseif ($name == '.') {
echo 'Current directory<br>';
continue;
}
if (is_dir($name) ) echo $name.' is a dir<br>';
elseif (is_file($name)) echo $name. ' is a filr';
else echo $name. ' что же это может быть?<br> ';
}
closedir($dir_hndl);
?>

Now I will briefly talk about the rest.
stat () - Gets information about the file (creation date, owner) as an array.
lstat () - Get information about a file or symbolic link.
file_exists () - Checks if a file or directory exists
is_writable () - Checks the ability to write to a file
is_readable () - Checks the ability to read from a file
is_executable () - Clarifies if the file is executable
filectime () , fileatime () , filemtime () , fileinode () , filegroup () , fileowner () , filesize () , filetype () , fileperms () - return information about the file. What - guess the name.

Questions to the head

1. What are the steps involved in working with files?

2. How to use the chdir () function to move to a directory one level higher without using the getcwd () function and other methods of recognizing the current directory?

3. Write a script that reads the lines from the f1.bmp file, sorts them and sorted the result, write them to the file f1.mp3.

4. Write a script that displays the / usr directory tree and skips files that are not allowed to write to. Hint: For this, remember the recursion.
The tree should look like this:
/ usr /
--local /
---- etc /
---- bin /
--home /
---- myfolder /
-------- my_file


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)