MySQL and Access databases are increasingly becoming publicly available storage tools. But in the early 1990s, working with files in PHP was popular, saving records in formatted text files in CSV format, separated by new lines.
Basic principles of work
Databases are convenient, but every developer should at least have some basic knowledge on how to read and write files. Perhaps many will reflect on the question: βWhy do I need to know this? If I use files, they are written in XML, and I just use a parser. "
So, here are a few reasons why you might need files:
- To move binary data (such as image files) to the BLOB database (binary large objects).
- Import data (such as email addresses) exported from an obsolete database or application.
- To export information from a database into a text file for offline processing.
Reading files and writing are basic operations. If you need to read a document, you must first open it. After that, read as much content as possible, then close the file. To write information to a document, you must first open it (or, possibly, create it if it has not already been created). After that, write the necessary data and close it upon completion.
It is also convenient to use the built-in functions that automatically open and close. They are available in PHP5. You should also familiarize yourself with the attributes of files, that is, with its properties.
They can tell:
- about the size;
- give out information about the last time he was contacted;
- talk about the owner, etc.
It is best to learn all the basic attributes for working with files in PHP. This will greatly facilitate the work.
File history
You may need to find out the time the file was last edited. In this case, functions come to the rescue: fileatime (), filemtime (), and filectime ().
<?php $formatDate = "D d MY g:i A"; $timeA = fileatime($file); $timeM = filemtime($file); $timeC = filectime($file); echo $file . " " . date($formatDate, $timeA) . ".<br>"; echo $file . " i- " . date($formatDate, $timeM) . ".<br>"; echo $file . " " . date($formatDate, $timeC) . ".";
Here, the code retrieves the timestamp of the last access and displays it:
- C: Windowsfile.ini was viewed on Sep 19, 2018 4:34 pm.
- C: Windowsfile.ini was changed Fri 8 Oct 2018 2:03 a.m.
- C: Windowsfil.ini was changed on Tue 16 Dec 2017 4:34.
The filectime () function shows the time of the change of various information related to the file (for example, access rights), and filemtime () shows the changes of the file itself.
The date () function was used to format the Unix timestamp returned by the file * time () functions.
File or not?
To find out if the work with files really works in PHP, you can use the is_file () function or is_dir () to check if this is a directory.
<?php echo $file . (is_file($file) ? " " : " ") . " .<br>"; echo $file . (is_dir($file) ? " " : " ") . " .";
Example code output:
- C: Windowsfile.ini file.
- C: Windowsfile.ini is not a directory.
Thus, you can avoid errors and not open inadvertently "not a file". In PHP, working with files and directories is similar.
File permissions
Before working with a file, you can check whether it is readable or writable. To do this, use the is_writable () and is_readable () functions.
<?php echo $file . (is_readable($file) ? " " : " ") . " .<br>"; echo $file . (is_writable($file) ? " " : " ") . " .";
These functions return a boolean and explain whether the operation can be performed in a file.
The code displays the following values:
- C: Windowsfile.ini is read.
- C: Windowsfile.ini is not being recorded.
Using the ternary operator, you can specify whether a file is available or not.
file size
To find out the file size, you need to use the filesize () function. It will be shown in bytes.
<?php $file = "C:\Windows\file.ini";$size = filesize($file); echo $file . " " . $size . " .";
The function displays the following:
- C: Windowsfile.ini is 510 bytes in size.
Using a file on a Windows system here emphasizes one caveat. A backslash has special meaning as an escape character. You will need to avoid this by adding another backslash.
If the file has not yet been created, the filesize () function will point to False and an error. Therefore, first check the file for the existence of the desired file_exists () command.
<?php $file = "C:\Windows\file.ini";if (file_exists($file)) { $size = filesize($file); echo $file . " " . $size . " .";}else { echo $file . " .";}
The file_exists () check should almost always be turned on for security.
Reading files
The previous section shows how much you can learn about the files you work with before you start reading or writing to them. Now you can understand how the contents of the file are read.
Functions for working with PHP files make the task easier. In this case, you need file_get_contents (). It will read the entire contents of the file into a variable without having to open or close the file on its own. This is convenient when the write volume is relatively small, since immediately reading 1 GB of data into the archive is not always rational in PHP. Work with .ini files and the file_get_contents () function are shown below.
<?php $file = "c:\windows\file.ini";$file1 = file_get_contents($file); echo $file1;
For large files or just depending on the needs of your script, it may be wiser to process the details yourself. This is due to the fact that as soon as the file is opened, you can search for a specific remark in it and read as much data as you want. The fopen () function is used to open a file.
<?php $file = "c:\windows\file.ini";$file1 = fopen($file, "r");
To use the fopen () function, two arguments are required:
- file to be opened;
- The mode used in this case is βrβ for reading.
The function returns a handle or stream to a file that is stored in the variable $ file1. It must be used in all subsequent commands when working with a file.
Common Mode ValuesMode | Value | Cursor position | If the file does not exist? |
r | only reading | beginning of file | will give an error |
w | record only | beginning of file | will create a new |
a | record only | end of file | will create a new |
To read one line at a time from an open file, you can use the fgets () function.
<?php $file = "c:\windows\file.ini";$file1 = fopen($file, "r"); do { echo fgets($file1) . "<br>";} while (!feof($file1)); fclose($file1);
Using a do-while loop is a good choice to know in advance how many lines are in the file. The feof () function checks if the file has reached completion and the loop continues until the end of the file condition is reached. After reading, use the fclose () function to close the document.
Recording files
Two commonly used modes when writing to a file using the fwrite () function: βwβ and βaβ. βWβ means that you need to write to the document, but it will delete any contents beforehand, βaβ - adding new data to what already exists in the file. You need to be sure that the correct option is used.
In the following example, βaβ mode will be used for recording.
<?php $myFile = "files.txt";$file1 = fopen($myFile, "a"); $output = "" . PHP_EOL;fwrite($file1, $output); $output = "" . PHP_EOL; fwrite($file1, $output); fclose($file1);
First, the file name is assigned to the variable, then it is opened in the βaβ mode for adding. The data to be written is assigned to the variable $ output and fwrite (), and the information is added to the file. The process is repeated to add another line, then the document is closed using fclose ().
The predefined constant PHP_EOL adds a newline character specific to the platform on which PHP works with text files.
The contents of the file after executing the above code should look like this:
The file_put_contents () function can also write to a file. It accepts the file name, the data to be written, and the FILE_APPEND constant if it should add data (it will overwrite the contents of the file by default).
Here is the same example as above, but this time using file_put_contents ().
<?php $myFile = "files.txt"; file_put_contents($myFile, "" . PHP_EOL); file_put_contents($myFile, "" . PHP_EOL, FILE_APPEND);
You have to work with these functions often, so itβs better to remember them. In addition, they can one day work with PHP files to ease some complex tasks.