Last Updated:

Accessing and manipulating files in PHP

manipulating files in PHP

PHP is a programming language whose interpreter resides on the server. The server has its own space for data storage. Therefore, it was logical to provide PHP with the ability to manipulate not only RAM, but also save data to permanent media.

One of the important abilities of PHP is to write and read text as well as binary files. Since PHP works with HTTP and FTP protocols, it becomes clear that it is capable of uploading not only text information, but also transferring data from audio, video and image files.

Opening files

Before you can work with a file, you must open it. For this purpose, the language provides the fopen($fname, $mode) function. The first parameter specifies the name of the file and the path to it, the second parameter specifies the opening mode for writing, reading, and others.

 

The path to the file is specified as a string and looks like this:

 

D:\documents\files\somefile.txt.

The second parameter is also a string and can get one of the following values:

  • The "r" is a readable discovery.
  • "w" is for recording.
  • "a" to continue recording while retaining the remaining data.

The possibilities are expanded if you add "+" to the parameter:

  • "r+" — for reading and writing.
  • "w+" — for writing and reading. If the specified file is not present, it is created.
  • "a+" — to continue recording with the creation of a file in the absence of it.

As you can see, if you put the "+" sign, then if there is no file in the specified path, it will be automatically created by the interpreter, and it will get the name from the first parameter of the function. If you do not set a plus, the function will return false if there is no file.

So, the call to the file open function is as follows: fopen("D:\documents\files\somefile.txt", "w");. If the file is missing, the interpreter will continue to execute the script. But you can interrupt its work and display an error. For this purpose, the ordie ("Arbitrary Error Text") construct is provided.

Let's look at an example:

fopen("D:\documents\files\somefile.txt", "w") ordie("Such a file does not exist, change the opening mode or create the file yourself");
fclose(«D:\documents\files\somefile.txt»); Close the file to save hardware resources.

It is not necessary to write a string path to the file. It's easier to save it to a variable so that when you open, close, and read it, you don't have to write the entire path.

Reading data from a file

There are several functions to read data from a file:

  1. fgets() — line-by-line reading, the function returns a file handle and a string that was subtracted. The next time the function is called, the next line after the previous one will be read.
  2. file_get_contents() — reads the entire file at once.
  3. fread() — reads a part of the information from the file, the size of which is determined by the parameter.

Let's look at an example:

$file = fopen("somehing.php", 'r') ordie(Couldn't open the file because it was missing");
while(!feof($file)) // feof indicates that the carriage has reached the end of the file
{
$str = htmlentities(fread($file, 600));
echo $str;
}
fclose($file);

After working out the cycle, 600 bytes of information will be displayed. The fread() function takes two parameters. The first is the open file and the string path to it. The second number of bytes to subtract. After some of the bytes have been read, the pointer stops where the last byte was read.

How do I write bytes or text to a file?

Similar to the read function in PHP, there is a function for writing fwrite(). It writes the string specified in the parameter.

Example:

$file = fopen(«D:\documents\files\somefile.txt», ‘w’) ordie(«Не получилось открыть файл ввиду его отсутствия»);
$str = «Привет, как дела?»;
fwrite($file, $str);
fclose($file);

At the beginning of the file, the line ""Hello, how are you?" will be written. We can also use the fputs() function, which works similarly to fwrite() and takes the same parameters.

Manipulating a File Pointer

If the file open mode without the "+" character is specified, the file carriage is set to the beginning of the file. Reading data is accompanied by moving the carriage to the end of the number of specified bytes or to the end of the file. But, is it really impossible to install the carriage in the desired place? Fortunately, PHP provides such a function and is called fseek().

The syntax for this function is as follows:

fseek(str $file , int $offset , int $offset_way = SEEK_SET/SEEK_CUR/SEEK_END);

The first parameter is a string literal and describes the path to the file, the second parameter indicates how many positions the carriage should be shifted relative to the current position. The third optional parameter can get only one of the 3 predefined constants:

  1. SEEK_SET sets the carriage to the top of the file,
  2. SEEK_CUR - the shift is carried out from the current position,
  3. SEEK_END — the offset will occur at the end of the file.

That is, the carriage is set to the beginning of the file, the end or remains in the current position, from this position and the offset parameter is offset.

Example:

$file = fopen("D:\documents\files\somefile.txt", 'w+') ordie("Cannot open a file that does not exist");
$str = «Helloeverybody!»; the string that we will write to the
file fwrite($file, $str); write a line to the beginning
of fseek($file, 0); place the carriage at the beginning
of the fwrite($file, "Haw are you?"); Write at the beginning
of fseek($file, 0, SEEK_END); place the pointer at the end
of fwrite($file, $str); Let's add another one to the existing entry, the one that we initialized at the beginning of the fclose($fd program
); Close the file stream

Useful functions for manipulating files and directories

The set of functions for manipulating files is not limited only to writing and reading. There are a number of functions that expand the capabilities of the programmer.

Move a file through directories

The rename(from, to) function moves the file to another directory.

Move file from directory D:\documents\files\somefile.txt в D:\documents:

if (!rename("D:\documents\files\somefile.txt", "D:\documents\files\somefile.txt"))
echo "An error occurred while moving";
elseecho "The file was moved successfully";

the first parameter of the function gets the current directory of the file to be moved, the second determines the location of its movement

Copy a file

The copy(from, to) function is responsible for copying files. In the first parameter, we specify the directory and name of the current file, in the second parameter we specify the location of copying the file, the name of another file where the content will be copied.

Example:

if (copy("D:\documents\files\somefile.txt", "D:\documents\copy.txt"))
echo "File copy succeeded";
elseecho "File not copied";

Delete a file

To delete a file in PHP, the unlink(f) function is provided. It takes a single string parameter that specifies the directory and the name of the file to be deleted.

Example:

if (unlink(«D:\documents\copy.txt))
echo "File successfully deleted";
elseecho "Mistake! The file was not deleted";

Let's sum up

Here we have seen the main features of PHP for manipulating the contents of files. The file can be written, opened, read data from it, deleted, copied. Reading is done line by line, in chunks, and the entire file. You can set the file pointer to any point.

What wasn't covered: Creating directories. Although we created the path to the file ourselves or prescribed the path for opening it, the PHP language has a rich functionality for manipulating directories. You can create directories, create new folders, delete them, rename them, and more.

The created director's office will become part of the program and it will not be possible to lose it without using the functions. It's like a constant that is fixed and doesn't change. In this directory, we can automate the functionality of file management, which is a reliable mechanism for the work of the site script.

Of course, a file is not a good way to store important data. For example, when creating a script that operates with user data, it is better to use a database. However, the file allows you to store large data, saves it and provides constant access. You can manipulate both text and other file formats. Since PHP is not a strongly typed language, the interpreter itself determines what data will go through the file stream.