It is very easy task to learn working with files in php. follow this steps to get master in working with files in php.
Reading a file: file_get_contents ()
Using the file_get_contents () function, you can get the contents of a file:
# Getting information from a file
$data = file_get_contents('data.txt');
We can also get the html-code of a page on the Internet:
But this does not work for all sites, many have protection against such primitive parsing.
Reading a file: file ()
The file () function allows you to get the contents of a file as an array. The element separator is a line feed character.
Create a data.txt file at the site root with the following content:
Now let’s run the index.php script with the following code:
$arr = file('data.txt');
When we run this script, we get in the browser:
Notice that the first two lines are 7 characters long instead of 5? This is because each line contains a line break at the end.
Most often we do not need them, so they can be removed by passing the FILE_IGNORE_NEW_LINES constant as the second parameter :
$arr = file('data.txt', FILE_IGNORE_NEW_LINES);
Now all lines will have 5 characters.
If we need to get only filled lines in the file and skip empty ones, we can pass the FILE_SKIP_EMPTY_LINES constant as the second parameter :
$arr = file('data.txt', FILE_SKIP_EMPTY_LINES);
Of course, we can pass two constants at once:
$arr = file('data.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
Create a file and write to a file: file_put_contents ()
The file_put_contents () function creates a file and populates it with data.
The function accepts the path to the file as the first parameter, and the data string as the second. To create an empty file, pass an empty string as the second parameter.
// Create a file and write the string 'Vasya' into it
file_put_contents ('data.txt', 'Vasya');
// Create an empty file
file_put_contents ('data.txt', '');
If the file does not exist, it will be created. If it exists, the data in the file will be overwritten.
In order not to overwrite the data, but to add it to the end of the file, you need to pass the FILE_APPEND constant as the third parameter :
file_put_contents('data.txt', 'Data', FILE_APPEND);
You can also pass an array as the second parameter:
file_put_contents('data.txt', ['One', 'Two', 'Three'], FILE_APPEND);
But this option is not very convenient, since all elements of the array will be written in a row, without any separators. To add them, you can use the implode function:
$arr = ['One', 'Two', 'Three'];
// Separate items with a comma
$str = implode (',', $ arr);
// Or you can separate them with a line break
$str = implode ("\ n", $ arr);
Create a folder or folder structure
You can create a folder using the mkdir () (make directory) function :
The second parameter specifies the permissions to the file as an octal number, by default it is 0777 , which means the widest rights. For Windows, this argument is ignored.
In addition, the second parameter can be ignored for the given umask (user mask, which is needed to determine the final access rights). In this case, you can forcibly change permissions using the chmod () function :
mkdir('new_folder', 0777, true);
We can also create the folder structure recursively, for this we need to pass true as the third parameter :
mkdir('folder1/folder2/folder3', 0755, true);
But in this case, the permissions will be set only for the destination folder. To change the rights for each of the folders, you will have to specify the rights manually:
mkdir('folder1/folder2/folder3', 0755, true);
// If you need to ignore the umask
Access rights are a separate large topic, so now we will not consider it for now.
Checking if a file or folder exists
You can check the existence of a folder or file using the file_exists () function :
File or folder exists';
If you want to check the existence of only a folder or only a file, there are special functions is_dir () and is_file () for this :
$path = 'data.txt';
echo 'This is a file';
elseif (is_dir ($ path))
echo 'This is a folder';
echo 'Not found';
Access rights check
The is_readable () and is_writable () functions check if the user on whose behalf PHP is running has read and write permissions to a file or folder:
$path = 'data.txt';
echo 'You have read permissions.';
if (is_writable ($ path))
echo 'Write permission available.';
Copying, moving and deleting a file
The unlink () function is used to remove files :
To copy a file, use the copy () function :
The rename () function is used to rename and move the file to another folder :
Working with files with fopen ()
The file () , file_get_contents (), and file_put_contents () functions are sufficient for most file management tasks.
But sometimes situations arise when we need more advanced tools. For example, if we have a large text file and we want to read it line by line, and not all at once, to save RAM.
So, you can open (or create and open) a file using the fopen () function :
# If there is no file, it will be created$f = fopen('data.txt', 'w');
The fopen () function returns a so-called descriptor. This is a link, a pointer to a file, we will pass it to other functions. By the way, the data type of this descriptor is resource .
The first parameter is the path to the file, the second is the file access modifier. The most popular modifiers are listed below:
- r – open for reading, the pointer goes to the beginning of the file.
- r + – open for reading and writing, the pointer goes to the beginning of the file.
- w – open for writing, the pointer goes to the beginning of the file. If there is no file, it is created, if there is, it is cleared of data.
- w + – open for reading and writing, otherwise similar to w .
- a – open for writing, the pointer goes to the end of the file. If there is no file, it is created.
- a + – open for reading and writing, otherwise similar to a .
- x – create and open for writing, the pointer goes to the beginning of the file. If the file exists, PHP will show an error.
- x + – create and open for reading and writing, otherwise the same as x .
A pointer is something like a cursor. You can move it anywhere in the file to add or edit specific data.
To write data to a file, there is the fwrite () function . Let’s try to create a file and write some data to it:
# If the file does not exist, it will be created, if it exists, it will delete the old data
$ f = fopen ('data.txt', 'w');
# Add something to the file
fwrite ($f, 'First record');
# Add something else
fwrite ($f, 'Second entry');
# Close the file connection
# Now the file contains the text "First Record Second Record"
Note that due to the w modifier , each time the script is run, the data in the file is erased and re-added. If the modifier is replaced with a , the data will not be overwritten, but appended to the end of the file.
To read the file line by line, use the fgets () function :
$f = fopen("data.txt", "r");
while($line = fgets($f, 4096))
echo $line, '<br>';
On each run fgets gets the next line and returns it in $line . The second parameter is the maximum length of the string. This means that if the line is too long, it will be truncated.
There are also many other useful functions in PHP that work with the file descriptor. You can read about them in the documentation .