Working with files in php: opening, writing, reading. How to properly read files using PHP Writing and reading a php file

Under working with files in PHP implied reading from file And write to file various information. It is quite obvious that you have to work with files a lot, so any PHP programmer must be able to read from file And write to file.

Subsequence working with files in PHP like this:

  1. Open file.
  2. Perform the necessary actions.
  3. Close the file.

As you can see, the sequence of working with files resembles working with files through a regular explorer. Only here all the work is done automatically by ourselves PHP script.

Let's start with the first point - opening the file. The file is opened with fopen() functions. The first parameter is the file path and the second parameter is modifier. Let's immediately look at the possible modifiers:

  1. a- opens the file for writing only, with the pointer placed at the end of the file.
  2. a+ a, but the file also opens for reading.
  3. r- opens the file for read-only, and the pointer is set to the beginning of the file.
  4. r+- same as modifier r, but the file is also opened for writing.
  5. w- opens the file for writing only, sets the pointer to the beginning of the file and erases the entire contents of the file.
  6. w+- same as modifier w, only the file is also opened for reading.

There are also two modes of working with files: binary(denoted b) And text(denoted t). If you are working with a regular text file, then select text mode, and if, for example, with an image, then select binary mode.

These are all the basic modifiers, which will be enough for you. Now let's learn how to close a file. Closes the file with fclose() functions.

Now let's move on to reading the file using fread() functions. And let me finally give you an example:

$contents = "";
while (!feof($handle))
$contents .= fread($handle, 4096);
fclose($handle);
?>

In this example, we first open the file for reading in text mode (modifier rt). fopen() function returns the so-called descriptor, with which you can communicate with the file, and write it to a variable handle. Then we're in a loop while() until the end of the file is reached, we read the contents each time 4096 characters that we write to the variable contents. After the reading process is completed, close the file, again using the file descriptor.

Now let's move on to recording using fwrite() functions:

$handle = fopen("files/a.txt", "at");
$string = "This is text";
fwrite($handle, $string);
fclose($handle);
?>

After running this script, in the file a.txt the line " will be added This is text".

Particularly attentive readers paid attention to the pointers that I wrote about just above. Pointer- this is the current position of the imaginary "cursor" in the file. This is where work with the file begins. You can change the position of the pointer using fseek() functions:

$handle = fopen("files/a.txt", "rt");
echo $contents."
";
fseek($handle, 0, SEEK_SET);
$contents = fread($handle, 3);
echo $contents."
";
?>

So we first read 3 character (as a result, the current pointer position is shifted by 3 positions). We then set the pointer to the beginning of the file. And we read again 3 symbol. As you might have guessed, we counted the same thing twice. That is the first time 3 symbol, then went back and counted again 3 symbol. Also if you fseek() functions replace SEEK_SET on SEEK_CUR, then the second parameter will not set the pointer position, but will shift it relative to the current location. I even advise you to practice with pointers, because it is not so easy to understand. I also recommend trying to write something to the file at the pointer position, for example, at the very beginning of the file. And be sure to explain your results.

And finally, I would like to give a couple more functions that allow you to work with files at the simplest level: file_put_contens() And file_get_contents(). Function file_put_contents() writes to a file, and the function file_get_contents() reads content from a file. These functions are very easy to use, but there are fewer options (although, as a rule, they are not needed):

file_put_contents("files/a.txt", "This is text 2");
echo file_get_contents("files/a.txt");
?>

In this script, we first wrote the line " This is text 2" to a file, and then we read the resulting content and output it. As you can see, it is difficult to come up with a simpler way reading from file And write to file.

That's all the main points working with files in PHP.

MySQL and Access databases are increasingly becoming publicly available data storage tools. But in the early 1990s, working with files in PHP was popular, saving records in CSV formatted text files separated by newlines.

Basic operating principles

Databases are convenient, but every developer should at least have some basic knowledge of how to read and write files. Many people may be thinking about the question: “Why do I need to know this? If I'm using files, they're written in XML and I just use the parser."

So here are a few reasons why you might need files:

  1. To move binary data (such as image files) into a BLOB (binary large object) database.
  2. Import data (such as email addresses) exported from a legacy database or application.
  3. To export information from a database to a text file for offline processing.

Reading files and writing are basic operations. If you need to read a document, you first need to open it. After this, you should read as much of the content as possible, then close the file. To write information into a document, you must first open it (or perhaps create it if it has not already been created). After this, record 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 file attributes, that is, its properties.

They can tell:

  • about the size;
  • provide information about the last time he was contacted;
  • tell about the owner, etc.

It's best to learn all the basic attributes for working with files in PHP. This will make the work much easier.

File history

You may need to find out when the file was last edited. In this case, the functions fileatime(), filemtime() and filectime() come to the rescue.

"; echo $file . " had last modified i-node " . date($formatDate, $timeM) . ".
"; echo $file . " has been modified " . date($formatDate, $timeC) . ".";

Here's the code that retrieves the last access timestamp and displays it:

  • C: Windowsfile.ini was accessed Sep 19, 2018 4:34 pm.
  • C: Windowsfile.ini was modified Fri Oct 8, 2018 2:03 am.
  • C: Windowsfil.ini was modified on Tue Dec 16, 2017 4:34 am.

The filectime() function shows the change time of various information associated with a file (for example, permissions), and filemtime() shows the change time 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 file manipulation is actually happening in PHP, you can use the is_file() function or the is_dir() function to check whether it is a directory.

"; echo $file . (is_dir($file) ? " " : " not") . " directory.";

Example code output:

  • C: Windowsfile.ini file.
  • C: Windowsfile.ini is not a directory.

This way you can avoid mistakes and not open a “non-file” by negligence. 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, you need to use the is_writable() and is_readable() functions.

"; echo $file . (is_writable($file) ? " " : " not") . " is written.";

These functions return a boolean value and explain whether the operation can be performed on the file.

The code will output the following values ​​to the screen:

  • C: Windowsfile.ini is being read.
  • C: Windowsfile.ini is not written.

Using the ternary operator, you can indicate whether a file is accessible or not.

file size

To find out the file size, you need to use the filesize() function. It will be shown in bytes.

The function will display the following:

  • C: Windowsfile.ini is 510 bytes in size.

Using the file on a Windows system highlights one point here. The backslash has special meaning as an escape character. You will need to escape this by adding another backslash.

If the file has not yet been created, the filesize() function will report False and an error. Therefore, they first check the file for the existence of the required file_exists() command.

The file_exists() check should almost always be enabled for security.

Reading files

The previous section showed how much you can learn about the files you're working with before you start reading or writing to them. Now you can figure out how the contents of the file are read.

Functions for working with PHP files make things easier. In this case, you will need file_get_contents(). It will read the entire contents of the file into a variable without having to open or close the file yourself. This is convenient when the recording volume is relatively small, since immediately reading 1 GB of data into an archive is not always rational in PHP. Working with “.ini” files and the file_get_contents() function is shown below.

For larger files, or simply depending on the needs of your script, it may make more sense to handle the details yourself. This is because once the file is opened, you can search it for a specific note and read as much data as you want. The fopen() function is used to open a file.

The fopen() function requires two arguments:

  • the file to be opened;
  • The mode used in this case is "r" for reading.

The function returns a handle or stream to a file, which is stored in the $file1 variable. It must be used in all subsequent commands when working with the file.

To read from an open file one line at a time, you can use the fgets() function.

";) while (!feof($file1)); fclose($file1);

Using a do-while loop is a good choice to find out in advance how many lines there are in a file. The feof() function checks to see if the file has reached completion and the loop continues until the end of the file condition is reached. After reading is complete, the fclose() function is used to close the document.

Recording files

Two commonly used modes when writing to a file using the fwrite() function are "w" and "a". "W" means what needs to be written to the document, but it will first delete any content, "a" means adding new data to what already exists in the file. You need to be sure that the correct option is used.

The following example will use "a" recording mode.

First the file name is assigned to a variable, then it is opened in "a" mode for appending. The data to be written is assigned to the $output variable 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 runs with text files.

The contents of the file after executing the above code should look like this:

  • banana;
  • China.

The file_put_contents() function can also write to a file. It takes the name of the file, the data to be written, and the constant FILE_APPEND if it should append data (will overwrite the default file contents).

Here's the same example as above, but this time using file_put_contents().

You need to work with these functions often, so it is better to remember them. In addition, they may one day make some complex tasks easier when working with PHP files.

Last update: 11/1/2015

Like most programming languages, PHP supports working with files, which are one of the ways to store information.

Reading and writing files

Opening and closing files

To open files in PHP, the fopen() function is defined. It has the following definition: resource fopen(string $filename, string $mode) . The first $filename parameter represents the path to the file, and the second is the opening mode. Depending on the purpose of opening and the type of file, this parameter can take the following values:

    "r" : The file is opened read-only. If the file does not exist, returns false

    "r+" : The file is opened read-only and writable. If the file does not exist, returns false

    "w" : The file is opened for writing. If such a file already exists, then it is overwritten, if not, then it is created.

    "w+" : The file is opened for writing and readable. If such a file already exists, then it is overwritten, if not, then it is created.

    "a" : The file is opened for writing. If such a file already exists, then the data is written to the end of the file, and the old data remains. If the file does not exist, it is created

    "a+" : The file is opened for reading and writing. If the file already exists, then the data is appended to the end of the file. If the file does not exist, it is created

The output of the fopen function will be a file descriptor. This handle is used for file operations and to close the file.

After finishing work, the file must be closed using the fclose() function, which takes a file descriptor as a parameter. For example, let's open and close a file:

$fd = fopen("form.php", "r") or die("could not open file"); fclose($fd);

The or die("error text") construct allows the script to stop running and display some error message if the fopen function was unable to open the file.

Reading a file

You can use several functions to read a file. For line-by-line reading, the fgets() function is used, which receives a file descriptor and returns one line read. Let's go through the entire file line by line:

Each time fgets() is called, PHP will place the pointer at the end of the line read. To track the end of a file, the feof() function is used, which returns true when the file is completed. And until the end of the file is reached, we can use the fgets() function.

Reading the entire file

In this case, we do not have to explicitly open the file, obtain a handle, and then close the file.

Block reading

You can also do a block-by-block read, that is, read a certain number of bytes from a file using the fread() function:

The fread() function takes two parameters: the file handle to read and the number of bytes to read. When a block is read, the pointer in the file moves to the end of that block. And also using the feof() function you can track the completion of a file.

Write a file

To write a file, use the fwrite() function, which writes the following line to the file:

Another fputs() function works similarly:

Working with the file pointer

When opening a file for reading or writing in "w" mode, the pointer in the file is placed at the beginning. When reading data, PHP moves the pointer in the file to the end of the block of data read. However, we can also manually manipulate the pointer in the file and set it to an arbitrary location. To do this you need to use the function fseek, which has the following formal definition:

Int fseek (resource $handle , int $offset [, int $whence = SEEK_SET ])

The $handle parameter represents a file handle. The $offset parameter is the offset in bytes relative to the beginning of the file from which reading/writing will begin. The third optional parameter specifies how the offset is set. It can take three values:

    SEEK_SET : default value, sets the offset in offset bytes relative to the start of the file

    SEEK_CUR : sets the offset in offset bytes relative to the beginning of the current position in the file

    SEEK_END : sets the offset to offset bytes from the end of the file

If the pointer is successfully installed, the fseek() function returns 0, and if the pointer is unsuccessful, it returns -1.

Example of using the function:

$fd = fopen("hello.txt", "w+") or die("could not open file"); $str = "Hello world!"; // line to write fwrite($fd, $str); // write the line to the beginning fseek($fd, 0); // place the file pointer at the beginning fwrite($fd, "Oink"); // write the line at the beginning fseek($fd, 0, SEEK_END); // place the pointer at the end fwrite($fd, $str); // write another line at the end fclose($fd);

And now there will be a fairly large, but not complicated lesson about working with files in PHP. First of all, what are the files for? After all, you can store everything in a MySQL or PostgreSQL or any other database. But sometimes there are tasks when using a database, with all the processing and concern for connection security, is not advisable. For example, we need to make a regular counter, but before this we did not use a database in the project. So, for the sake of one tiny counter, should we create a database and store just a couple of lines in it? It's much easier to use files here. In addition, sometimes the hosting does not support databases at all, then files are generally the only option.

Well, let's say I convinced you that the files are necessary :) Now let's figure out how to work with them. How to create, open, write, overwrite, read and so on. First things first.

Create a file

PHP uses the fopen function to open files. However, it can also create files. If you pass fopen a file name that doesn't exist, it will create it.

The fopen function itself takes two parameters, both of which are required. First, we must specify the name of the file we want to open. Second, pass a parameter that tells the function what we plan to do with this file (for example, reading from the file, writing, etc.).

If we need to create a file, then we specify its name and pass the parameter that we want to write data to it. Note: We must be sure to tell PHP what we are writing to the file, otherwise it will not create a new file.

Example:

$ourFileName = "testFile.txt";

$ourFileHandle = fopen($ourFileName, "w") or die("can"t open file");

fclose($ourFileHandle);

The first line $ourFileName = testFile.txt creates a string variable in which we will store the file name.

The second line $ourFileHandle = fopen($ourFileName, ‘w’) or die(“can’t open file”) respectively creates or opens an existing file for writing. Or it returns a message that it cannot open the file.

The third line fclose($ourFileHandle) closes the file. It's actually simple.

File opening options in php

The first parameter 'r' (read) - opens the file for read only; you cannot write to it.

The second parameter ‘w’ (write) – opens for writing. In this case, the recording will always go from the beginning of the file. If there is already some information there, it will be overwritten.

The third parameter 'a' (append) - opens the file for writing, but will append to the end of the file, unlike w.

Advanced options:

Parameter 'r+' - opens for both reading and writing. The pointer will be at the beginning of the file.

Parameter 'w+' - opens for both reading and writing, BUT deletes all the information that was in the file!!!

parameter 'a+' - opens for reading and writing, but the pointer will be at the end of the file.

Naturally, only one of these parameters can be passed to a function, and not several. They need to be substituted for 'X":

fopen($ourFileName, "X")

Write to file

Well, now we have opened the file, selected the parameter we need, what next? You need to write something in it. How to do it? Using the fwrite function, which takes as parameters a pointer to a file and a line of text that we want to write. Example:

$myFile = "testFile.txt";

$fh = fopen($myFile, "w") or die("can"t open file");

$stringData = "First line";

fwrite($fh, $stringData);

$stringData = "Second line";

fwrite($fh, $stringData);

We created a file testFile.txt, the pointer to it is stored in the $fn variable. We wrote the line “First line” into it (at the end we used the end-of-line symbol n), and then “Second line”. Then they closed the file.

ATTENTION! Never forget to close your files! Otherwise, if the script execution terminates abnormally, the data in the files will not be saved! Always use fclose after work!!!

Reading from a file

We've written it down, now let's read it! It's not that difficult either. We use the fread function. As input we give it a pointer to the file and the number of bytes we want to read. For example, one character is equal to one byte (depending on the encoding), we want to read 5 characters: $theData = fread($fh, 5).

But if we need to get all the information that is in the file, then we will need the filesize function, which returns the number of bytes in the file, therefore, if the result of the filesize function is passed to fread, then we will get all the information from the file:

$myFile = "testFile.txt";

$fh = fopen($myFile, "r");

$theData = fread($fh, filesize($myFile));

I hope I explained it clearly.

$myFile = "testFile.txt";

$fh = fopen($myFile, "r");

$theData = fgets($fh);

As a result, we get the first line from the testFile.txt file. Accordingly, to go through all the lines you need to use a foreach loop:

$lines = file("testFile.txt");

foreach($lines as $single_line)

echo $single_line . "
n";

Now you have learned how to open files for reading, writing, or both. Write data to them or append them on top using Append, and also read information from them.

If you are learning to work with PHP on your own, then it is important to learn how to read data from a file and make changes to it. Recording in the php file is carried out for the development of web applications, changes to server information and launching external programs and inclusions.

How to work with php files

If a file has such an extension, it means it contains program code written in the programming language of the same name. In order to make changes, you will need to install one of the software editors on your PC:

PHP Expert Editor;
. Dreamweaver;
. Eclipse PHP Development;
. PHPEdit.

If you are creating a website, then you often need to use identical designs, which are conveniently stored as templates in another file. For this it is better to use include. After entering this function, you need to write the name and extension of the connection in the php file, for example, include 1.php. This design supports multiple readings of the included file, and an additional feature is the continuity of code execution in the event of an error. If something goes wrong, the code will continue to be executed from a new line.
This way you will include the file in your code. Another way is to enter require. Unlike the include described above, the file is included before the program code starts executing, but you can access it only once.

File verification

Before you write to a php file, you need to make sure that it exists, and then open it and do the necessary editing. To do this, you can use the file_exists() function; if it confirms the presence, then the response TRUE will be returned in the editor window, otherwise - FALSE.
Another function is_file() can notify you that it is possible to write data to a php file. It is more reliable than file_exits, and most programmers use is_file to get started. Once you have verified that the file exists, you can begin working with it.

Making changes to a file

The first tool you can use to make changes to a file is fwrite(). It writes lines with the following syntax:

Int - manipulator;
. String is a variable.

There is another function similar to this - fputs(), which is an alias. There are no differences between these tools; you can choose one or the other. For students, fwrite is more common, while practicing programmers most often use fputs.

To make a PHP entry into a text file, one important condition must be met - it must be open for editing. This file must be located in a folder with write permissions.

To work, try first opening a text document in the program, and then making edits using regular tools.

// Open a text file
$f = fopen("text.txt", "w");
// Write a string of text
fwrite($f, "Hello! Good day!");
// Close text file
fclose($f);

In this example, text.txt is the document name. You can call it differently: “Hello! Good day! - an example of text, it can be completely arbitrary. All changes are automatically saved in the open file.

Note that PHP is general purpose. It is intensively used to create web applications. This solution is supported by most hosting providers. We are talking about the leader among the tools that are used to create websites. Now you know how to write to a php file.