Computers Windows Internet

Php read a line from a file. Working with files in php: opening, writing, reading. Files: operating modes

PHP

file_exists ("test.txt") // Does the file exist? filesize ("test.txt"); // Find out the size of the file // Return the timestamp: fileatime ("test.txt"); // Date of the last access to the file // date ("d M Y", $ atime); filemtime ("test.txt"); // Date of file modification // date ("d M Y", $ mtime); filectime ("test.txt"); // Date the file was created (Windows) // date ("d M Y", $ ctime);

Files: operating modes

PHP

resource fopen (string filename, string mode) // resource - returns a file pointer on success, or FALSE on error
Working hours Description
r open file read-only;
r + open a file for reading and writing;
w open file for writing only. If it exists, then the current content of the file is destroyed. The current position is set to the beginning;
w + open the file for reading and writing. If it exists, then the current content of the file is destroyed. The current position is set to the beginning;
a open the file for writing. The current position is set to the end of the file;
a + open the file for reading and writing. The current position is set to the end of the file;
b process a binary file. This flag is required when working with binaries on Windows.

Opening and Closing Files in PHP

PHP

$ fi = fopen ("test.html", "w +") or die ("Error"); // Examples $ fi = fopen ("http://www.you/test.html", "r"); $ fi = fopen ("http://ftp.you/test.html", "r"); // Close fclose ($ fi)

Reading files in PHP

PHP

// Read the file fread (int fi, int length) $ str = fread ($ fi, 5); // Read the first 5 characters echo $ str; // since the cursor has moved $ str = fread ($ fi, 12); // Read the next 12 characters echo $ str; fgets (int fi [, int length]) // Read a line from a file fgetss (int fi, int length [, string allowable]) // Read a line from a file and discard HTML tags // string allowable - tags that need to be left fgetc (int fi) // Reads A Character From A File

Initially, Writing will occur to the beginning of the file, by overwriting existing data, if any. Therefore, if you need to write something to the end of the file, you need to set the corresponding reading mode for example a +.

Cursor manipulation in PHP files

PHP

int fseek (int fi, int offset [, int whence]) // Setting the cursor // int fi - a pointer to the file // offset - the number of characters to move. // whence: // SEEK_SET - movement starts from the beginning of the file; // SEEK_CUR - movement starts from the current position; // SEEK_END - movement starts from the end of the file. fseek ($ fi, -10, SEEK_END); // Read the last 10 characters $ s = fread ($ fi, 10); $ pos = ftell ($ fi); // Find out the current position rewind ($ f) // reset the cursor bool feof ($ f) // end of file

Working with files (data) directly in PHP

PHP

array file (string filename) // Get the contents of the file as an array // Another option for direct work with data file_get_contents (string filename) // Reading (we get the entire file in one line) // Writing to the file (initially overwritten) file_put_contents (string filename, mixed data [, int flag]); // FILE_APPEND // Writing to the end of the file: file_put_contents ("test.txt", "data", FILE_APPEND); // If we write an array, $ array = array ("I", "live"); file_put_contents ("test.txt", $ array); // then we get "Ilive"

Php file management

PHP

copy (string source, string destination); // Copy the file rename (str oldname, str newname); // Rename the file unlink (string filename); // Delete file

Uploading files to PHP server

// PHP.ini settings file_uploads (on | off) // enable. Disable uploading files upload_tmp_dir // temporary folder for uploaded files. default temporary folder upload_max_filesize (default = 2 Mb) // max. size of the uploaded file post_max_size // total size of the submitted form (must be greater than upload_max_filesize) // Simple upload

Html

We work with files on the server

PHP

// Receive data $ tmp = $ _FILES ["userfile"] ["tmp_name"]; $ name = $ _FILES ["userfile"] ["name"]; // Move the file move_uploaded_file ($ tmp, name); move_uploaded_file ($ tmp, "upload /". name); // redirect the file to the upload folder // relative to the current file // What's in the $ _FILES array $ _FILES ["userfile"] ["name"] // file name, for example, test.html $ _FILES ["userfile"] [" tmp_name "] // temporary file name (path) $ _FILES [" userfile "] [" size "] // file size $ _FILES [" userfile "] [" type "] // file type $ _FILES [" userfile "] ["error"] // 0 - no errors, number - yes

When studying this topic, keep in mind that some PHP functions use the file descriptor to access a file, while others use the file path.

Reading from a file

The fread () function can be used to retrieve a specified amount of data from a file.

fread (file, length)

Options:

file - file descriptor

length - the size of the data in bytes

If the end of the file is reached before the function reads the specified data size, it will return a smaller string. This function useful for reading binary files.

When specifying the length of the string and when moving the pointer, you need to take into account that Russian letters are not one byte in size, but more. For more information, see Working with Strings. Also, don't forget that there are several bytes at the beginning of the UTF-8 encoded file. In UTF-8 encoding without BOM, these bytes are missing.

Let's read the first 10 bytes from the myfile.txt file. Let's open it in "r +" mode. The pointer will be at the beginning.

$ file = fopen ("myfile.txt", "r +"); $ take = fread ($ file, 10); echo $ take;

If the file contains Russian letters, then the last letter may be displayed incorrectly. This is because the character is more than one byte in size and one part has been read and the other has not.

The fgets () function returns one string, starting from the pointer to the end of the string.

fgets (file, length)

Options:

file - file descriptor

length - allows you to specify the size of the string in bytes. Moreover, if the end of the line is reached, the next line is not included in the result of the function, even if the line is less than the specified length. Optional parameter.

If no length is specified, then in older versions of PHP the maximum length of the returned string was limited. Newer versions do not have this limitation.

Running the function in a loop allows you to read the file line by line.

Let's read one line from the file myfile.txt. Since the pointer has already been moved, not the entire line will be read, but from the pointer.

$ take = fgets ($ file); echo "
". $ take;

The fgetss () function also returns one string, but removes HTML tags from it. If a PHP script is present in the code, then it will also be removed.

fgetss (file, length, desired tags)

Options:

file - file descriptor

length - the size of the string in bytes. Optional parameter.

required tags - allows you to specify tags that will not be deleted.

There is a fgetc () function that returns one character from a file.

The file () function reads the entire file and puts the data into an array. Each line is placed into an element of the array. You do not need to open a file for this feature to work. The location of the pointer is ignored.

file (file path, flags, context)

Options:

file path - absolute or relative file path

flags - flags that determine how the function works. Optional parameter.

context - allows you to specify a context resource

You can specify the following flags:

FILE_USE_INCLUDE_PATH - allows you to search for a file in the include path folders.

FILE_IGNORE_NEW_LINES - removes the end-of-line character. If this flag is not set, then there will be an end-of-line character on each line.

FILE_SKIP_EMPTY_LINES - does not add empty lines to the array.

If multiple flags are specified, they are separated by the "|" operator.

Let's display the file myfile.txt on the page.

$ ar = file ("myfile.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); echo "
"; print_r ($ ar);

Write to file

The fwrite () function writes data to a file.

fwrite (file, data, length)

Options:

file - file descriptor

data - the data that is being written

length - the maximum size of the data to be written in bytes. Not the entire line can be written, but only the specified number of bytes. Optional parameter.

If the pointer is at the beginning or in the middle of the file, the function replaces the characters in the file with new ones. That is, if 5 characters are written, then 5 characters are removed from the file and new ones are added in their place.

When you write Russian letters, the script encoding must match the file encoding.

Let's write the line "text from the script" to the file. In our example, the descriptor is in the middle of the file and the line will be written there. When you need to add data to the end of the file, you can open it in "a" mode. And when a file needs to be overwritten, it is opened in "w" mode. We will not move the pointer, we will write the data to where it is.

$ text = "text from script"; fwrite ($ file, $ text);

Using the fopen, fclose, feof, fgets, fgetss, and fscanf functions

Let's list all the possibilities

One of the benefits of working with modern programming languages ​​like PHP is the sheer amount of capabilities available. PHP could easily have adopted the Perl motto, "There are multiple ways to do something," especially when it comes to file handling. But with the plethora of funds available, the question arises which one is the best for getting the job done. Of course, in reality, the answer to this question depends on what goals you set when processing the file, so learning all the features of the language is worth the time.

Traditional fopen methods

The fopen methods are perhaps more familiar to the C and C ++ programmers of the old days, as they are, to a greater or lesser extent, exactly the tools that have been at your fingertips for many years if you have worked with these programming languages. For any of these methods, you follow a standard procedure, using fopen to open the file, a function to read the data, and then fclose to close the file, as shown in Listing 1.

Listing 1. Opening and Reading a File with fgets
$ file_handle = fopen ("myfile", "r"); while (! feof ($ file_handle)) ($ line = fgets ($ file_handle); echo $ line;) fclose ($ file_handle);

While these functions are familiar to most experienced programmers, let me analyze how they work. In reality, you are following these steps:

  1. Open the file. $ file_handle stores a link to the file itself.
  2. Check to see if you have reached the end of the file.
  3. Continue reading the file until you reach the end, printing every line you read.
  4. Close the file.

With that in mind, I'll go over every file function used here.

Fopen function

The fopen function establishes a link to a file. I say "connects" because, in addition to opening a file, fopen can also open a URL:

$ fh = fopen ("http://127.0.0.1/", "r");

This line of code creates a link to the above page and allows you to start reading it as a local file.

Note: The "r" parameter used in fopen indicates that the file is open read-only. Since writing to a file is beyond the scope of this article, I will not list all the possible values ​​of the parameter. However, you need to change "r" to "rb" if you are reading from binaries for cross-platform compatibility. An example of this type will be given below.

Feof function

The feof command determines whether a read has been made to the end of the file and returns True or False. The loop given in continues until the end of the file "myfile." Note that feof also returns False if you are reading a URL and the connection timed out because there is no more data to read.

Fclose function

Skip the middle of Listing 1 and go to the end; fclose does the opposite of fopen: it closes the connection to a file or URL. After executing this function, you will no longer be able to read from a file or socket.

Fgets function

Going back a few lines in Listing 1, you are right at the heart of the file handling process: directly reading the file. The fgets function is your "weapon" of choice for the first example. It grabs a line of data from a file and returns it as a string. From there, you can output data or otherwise process it. The example in Listing 1 prints the entire file.

If you decide to limit the size of the chunk of data you are working on, you can add an argument to fgets to limit the maximum length of the captured data line. For example, use the following code to limit the string length to 80 characters:

$ string = fgets ($ file_handle, 81);

Think of "\ 0", the end-of-line in C, and set the length to one more character than you actually need. As you can see, the example above uses 81, whereas you need 80 characters. Make it a habit to add an extra character whenever you need to set a string length limit for a given function.

Fread function

The fgets function is just one of the many functions available for reading a file. This is one of the most commonly used functions, as line-by-line processing of a file is most sensible in most cases. In fact, several other features offer similar capabilities. However, line-by-line analysis is not always what you want.

And this is where we turn to fread. The fread function is used for a slightly different purpose than fgets: it is intended to read from binaries (that is, files that are not originally human-readable text). Since the concept of "strings" is not relevant for binary files (logical data structures are usually not broken into lines), you must specify the number of bytes to read.

$ fh = fopen ("myfile", "rb"); $ data = fread ($ file_handle, 4096);

The above example reads 4096 bytes (4 KB) of data. Note that regardless of the value you specify, fread will read no more than 8192 bytes (8 KB).

Assuming the file is no more than 8 KB, the code snippet below should read the entire file on one line.

$ fh = fopen ("myfile", "rb"); $ data = fread ($ fh, filesize ("myfile")); fclose ($ fh);

If the file is larger, you will have to use a loop to read the rest of the file.

Fscanf function

Returning to line processing, note that fscanf is also the successor to the traditional file-based C library function. If you are not familiar with it, fscanf reads data fields into variables from a file.

list ($ field1, $ field2, $ field3) = fscanf ($ fh, "% s% s% s");

The formatting strings used in this function are documented in many sources such as PHP.net, so I will not repeat this information here. Suffice it to say that string formatting is very flexible. It should also be mentioned that all fields are placed in a variable returned by the function. (In C, they would be passed as arguments.)

Fgetss function

The fgetss function is different from traditional file functions and gives you a better idea of ​​what PHP can do. It works like fgets, but it strips away any HTML or PHP tags it encounters, leaving only "bare" text. Let's take the below HTML file.

Listing 2. Sample HTML file
My title

If you understand what "Cause there ain" t no one for to give you no pain "means then you listen to too much of the band America

Let's run it through the fgetss function.

Listing 3. Using fgetss
$ file_handle = fopen ("myfile", "r"); while (! feof ($ file_handle)) (echo = fgetss ($ file_handle);) fclose ($ file_handle);

Here's what you get as output:

My title If you understand what "Cause there ain" t no one for to give you no pain "means then you listen to too much of the band America

Fpassthru function

Regardless of how you read the data from the file, you can print the remaining data using the standard output pipe using the fpassthru function.

fpassthru ($ fh);

This function prints the data, so you don't need to put it into a variable.

Nonlinear file processing: moving through the file

Of course, the above functions only allow you to read from a file sequentially. More complex files may require you to move to different parts of the file at the beginning or end. To do this, you need the fseek function.

fseek ($ fh, 0);

The above example jumps back to the beginning of the file. If you don't want to move to the very beginning of the file - say, one kilobyte is sufficient - you simply write:

fseek ($ fh, 1024);

As of PHP V4.0, several other options are also available. For example, if you need to jump forward 100 bytes from your current position, you can use the following code:

fseek ($ fh, 100, SEEK_CUR);

Likewise, jumping back 100 bytes is done by:

fseek ($ fh, -100, SEEK_CUR);

If you want to jump back to 100 bytes before the end of the file, use SEEK_END instead.

fseek ($ fh, -100, SEEK_END);

Once you've reached your new position, you can use fgets, fscanf, or another function to read the data.

Note: you cannot use fseek on file descriptors referencing URLs.

Capturing an entire file

We now turn to look at some of PHP's unique file handling capabilities: handling large blocks of data in one or two lines. For example, how can you grab a file and display all of its contents on your Web page? Well, you've seen an example of using a loop with fgets. But how can you make it easier? The process is almost ridiculously simple with fgetcontents, which puts the entire file on a string.

$ my_file = file_get_contents ("myfilename"); echo $ my_file;

Although not the best option, you can write this command even shorter:

echo file_get_contents ("myfilename");

This article is primarily about handling local files, however, it is worth noting that you can also capture, display, and parse other Web pages using the functions described.

echo file_get_contents ("http://127.0.0.1/");

This command is actually the same as:

$ fh = fopen ("http://127.0.0.1/", "r"); fpassthru ($ fh);

You must be looking at these examples and thinking, "This is still too time consuming." PHP developers agree with you. Therefore, you can shorten the above command to:

readfile ("http://127.0.0.1/");

The readfile function writes the entire contents of a file or Web page to the output buffer by default. By default, this command displays an error message on failure. To avoid this behavior (if you want it), try the command:

@readfile ("http://127.0.0.1/");

Of course, if you need to process the contents of files, then the one line returned by file_get_contents is probably too much. You might want to split it into parts first using the split () function.

$ array = split ("\ n", file_get_contents ("myfile"));

But why do you need all these complications if there is a perfectly suitable function that will do the job for you? The PHP file () function does this in one step: it returns a string array whose elements are the strings of the file.

$ array = file ("myfile");

It should be noted that there is a slight difference between the two examples above. The split command removes newlines, while the file command ends with newlines (just like with fgets).

PHP's capabilities, however, far exceed those described above. You can parse entire PHP style .ini files with just one command parse_ini_file. The parse_ini_file command applies to files similar to those in Listing 4.

Listing 4. An example .ini file
; Comment name = "King Arthur" quest = To seek the holy grail favorite color = Blue Samuel Clemens = Mark Twain Caryn Johnson = Whoopi Goldberg

The following commands represent a file as an array and then print that array:

$ file_array = parse_ini_file ("holy_grail.ini"); print_r $ file_array;

This will produce the following output:

Listing 5. Output
Array (=> King Arthur => To seek the Holy Grail => Blue => Mark Twain => Whoopi Goldberg)

Of course, you can see that this command has merged sections. This is the default, but you can easily make the necessary adjustments by using the second argument to parse_ini_file: process_sections, which is a Boolean variable. Set process_sections to True.

$ file_array = parse_ini_file ("holy_grail.ini", true); print_r $ file_array;

And your output will look like:

Listing 6. Output
Array (=> Array (=> King Arthur => To seek the Holy Grail => Blue) => Array (=> Mark Twain => Whoopi Goldberg))

PHP places data in a multidimensional array that can be easily parsed for analysis.

But that's just the tip of the iceberg when it comes to file handling in PHP. More complex functions such as tidy_parse_file and xml_parse can help you parse HTML and XML documents, respectively. See the section for more information on how these functions work. Both of them are worth considering if you work with these types of files, but instead of looking at all possible file types, you can carefully read the contents of this article, where there are some good general rules for working with the functions I have described so far.

Good programming style

Never assume that everything in your program will work as intended. For example: what if the file you are looking for has been moved? What if, as a result of a change in permissions, you cannot read the contents of the file? You can check in advance for the existence of a file and permissions to read it using the file_exists and is_readable methods.

Listing 7. Using file_exists and is_readable
$ filename = "myfile"; if (file_exists ($ filename) && is_readable ($ filename)) ($ fh = fopen ($ filename, "r"); # Processing fclose ($ fh);)

However, in practice, this piece of code will be, perhaps, excessive for your task. Handling the values ​​returned by fopen is simpler and more accurate.

if ($ fh = fopen ($ filename, "r")) (# Processing fclose ($ fh);)

Since fopen returns False on failure, this ensures that the file is processed only if the file can be opened. Of course, if the file doesn't exist or is unreadable, you would expect the return value to be negative. Therefore, such a check is a trap in which all potential problems fall. Alternatively, you can use program termination or display an error message if the file cannot be opened.

Like fopen, the file_get_contents, file, and readfile functions return False if the file cannot be opened or processed. The fgets, fgetss, fread, fscanf, and fclose functions also return False on error. Of course, with the exception of fclose, you've probably already processed the results they return. As far as fclose is concerned, there is little that can be done if the file descriptor does not close properly, so checking the return value of fclose is usually overkill.

The choice is yours

PHP has no shortage of efficient ways to read and parse files. Classic functions like fread can serve you reliably most of the time, or you may be more attracted to the simplicity of readfile if necessary to complete the task. The choice really depends on what you are trying to accomplish.

If you are processing large amounts of data, fscanf is likely to be more useful and efficient than, say, using file in conjunction with the subsequent split and sprintf commands. Alternatively, if you are simply displaying large text with minor changes, the file, file_get_contents, or readfile functions may be more appropriate. This solution is likely to be correct when using PHP for caching or even creating a temporary proxy.

PHP provides many tools for working with files. Get to know each of them better and find out which tools are best for the project you are working on. You are offered a wide variety of software tools, use them most effectively and have fun processing your files with PHP.

In PHP, you often have to deal with the creation of a file ... everything is very simple there is no file on the disk, the code ran and the file appeared, then you can read this file into another variable or even any page on the Internet and then write something there ... but for this you need to know special functions ... more about this in this article ...

To create a php file in the executable script, you just need to specify a few functions:

Let's consider an example right away:

$ text = "Some text here to write to the file";
$ fp = fopen ("file.txt", "w");
fwrite ($ fp, $ text);
fclose ($ fp);
?>

Here you should know:

fopen ()- the function opens the file for reading or for writing and refinements;

These refinements (the mode parameter of the fopen function) are very important:

  • "r"- open file in php Only for reading... The cursor is placed at the beginning.
  • "r +"- open file in php for reading and for writing... The cursor is placed at the beginning. !!! - with these two modes r and r +, the files must already be created (otherwise an error will come out Warning: fopen (file.txt): failed to open stream: No such file or directory in ...), and we only read or we have the opportunity to add.
  • "w"- the file is opened ONLY for writing. The file is truncated to zero length - that is, it is overwritten. It is written what is needed and the Cursor is placed at the beginning.
  • "w +"- the file is opened for writing AND READING! The rest is the same as in the" w "mode. !!! - with these two modes - if the file was not created - ATTEMPT TO CREATE IT!
  • "a"- open the file ONLY for writing. Unlike" w ", this parameter does not overwrite the contents of the file, but puts the cursor at the end of the line and appends the content that we wanted to add to the end.
  • "a +"- open a file for writing and reading.

fwrite($ fp, $ text) - the function of writing to a file in php - that is, what is in the variable $ text is written to the file, which is in the variable $ fp;

fclose($ fp) - the function of closing the file that we have written to the $ fp variable;

All now you can safely create correctly files in php, open them for reading and editing.

Useful PHP add-ons and functions for working with an open file:

while (! feof ($ fp)) (
$ mytext = fgets ($ fp, 99);
echo $ mytext. "
";
}

here the condition is fulfilled - "until the end of the file is reached, then do that" while (! feof ($ fp))

1. Function fgets($ fp, 99) - allows you to divide all content into sections of 99 bytes and further, to see this more clearly we put a tag

This string function fgets(resource handle [, int length]) by default accepts a length of 1024 bytes (1 kilobyte), if not specified it will. This parameter is optional since PHP 4.2.0 (Returns FALSE on error)

Additional functions for opening, writing and creating a file

Function - int readfile(string filename [, bool use_include_path [, resource context]]) - read the file as a whole.

Reads a file and writes the contents to the output buffer. And it returns the number of bytes printed. In case of an error, it will return, if the dog is not used - @readfile.

Something like this will turn out:

At the end of a word, the tag is
.

b. Function - array file(string filename [, int use_include_path [, resource context]]) does the same as the readfile function, with one exception, it adds the contents of the file to the array:

Thus, you can read any pages on the Internet: $ lines = file ("http: // site /"); and iterate over the array through the foreach function;

3a. String function file_get_contents(string filename [, bool use_include_path [, resource context [, int offset [, int maxlen]]]]) - allows you to get the content as a single line.

It is more versatile PHP function to read a file, similar to the file function, only the content is returned to a string, not an array, and you can specify conditions - which byte to start with - offset and which one to end with - maxlen... Returns FALSE on failure.

Important!!!- in this case, the function replaces 3 at once: fopen (), fread () and fclose () and thus gets rid of the stamps.

3b. Int function file_put_contents(string filename, mixed data [, int flags [, resource context]]) - identical to the sequential call of the fopen (), fwrite () and fclose () functions - returns the number of bytes written.

Every programmer should be able to work with files correctly. This article is aimed at novice PHP programmers, however, the "collection of recipes" will be useful for advanced users.

Working with files is divided into 3 stages:

  1. Opening a file.
  2. Data manipulation.
  3. Closing the file.

I. Opening a file

In order to open a file in the PHP environment, use the function fopen ()... The required parameters for this function are the file name and the file mode.

$ fp = fopen ("counter.txt", "r");

According to the PHP documentation, the following types of file modes are distinguished:

  1. r - open file read-only.
  2. r + - open a file simultaneously for reading and writing.
  3. w - create a new empty file. If at the time of the call such a file already exists, then it is destroyed.
  4. w + - is similar to r +, only if such a file exists at the time of the call, its contents are deleted.
  5. a - opens an existing file in write mode, while the pointer is shifted to the last byte of the file (to the end of the file).
  6. a + - opens a file in read and write mode, while the pointer is shifted to the last byte of the file (to the end of the file). The contents of the file are not deleted.

Note: there can be one more optional parameter at the end of any of the lines: b or t. If b is specified, then the file is opened in binary read / write mode. If t, then the line feed translation mode is set for the file, i.e. it is perceived as textual.

For a demonstration, consider the following scenario:

// Opens the file in different modes
$ fp = fopen ("counter.txt", "r"); // Binary mode
$ fp = fopen ("counter.txt", "rt"); // Text mode
$ fp = fopen ("http://www.yandex.ru", "r"); // Opens an HTTP connection for reading
$ fp = fopen ("ftp: // user: [email protected]"," w "); // Open FTP connection with login and password
?>

II... File data manipulation

Write data to file when PHP help you can use the function fwrite ()... This function takes 2 required parameters and 1 optional. The required parameters are file descriptor and file mode:

$ fp = fopen ("counter.txt", "a"); // Open the file in write mode
$ mytext = "We need to write this line \ r \ n"; // Source string
$ test = fwrite ($ fp, $ mytext); // Write to file
if ($ test) echo "The data has been successfully entered into the file.";
else echo "Error writing to file.";
fclose ($ fp); // Close the file
?>

To read the file line by line, use the function fgets ()... The function takes 2 required parameters:


if ($ fp)
{
while (! feof ($ fp))
{
$ mytext = fgets ($ fp, 999);
echo $ mytext. "
";
}
}

fclose ($ fp);
?>

Note: B this example the value 999 determines the number of characters that will be read until the pointer reaches the end of the file (EOF).

In order to read the file as a whole, you need to use the function readfile () that takes 1 required parameter. The function opens a file, displays its contents in a browser window, and then closes the file:

echoreadfile ("counter.txt");
?>

You can also use the fpassthru () function which takes 1 required parameter. Before using this function, you must open the file in read mode. When the file is finished reading, the function automatically closes the file (and the file descriptor becomes invalid).

$ fp = fopen ("counter.txt", "r"); // Open the file in read mode
if ($ fp) echo fpassthru ($ fp);
elseecho "Error opening file";
?>

Very often there are situations when it is necessary to read the content of the site into an array. This feature is provided by using the function file ()... When this function is called, each line of the file will be saved in a separate element of the specified array.

Note: Do not use the function file () to binary files (binary-safe), because it is not safe in terms of reading binary files, if at the same time, somewhere there is an end-of-file (EOF) character, then it does not guarantee you reading the entire binary file.

$ file_array = file ("counter.txt"); // Read the file into $ file_array
// Work with array data
?>

Note: Working with arrays is described in detail, authors: Mukhametshin D.F., Simdyanov I.V.

At the end of the article, you will find a good "recipe book" for arrays that provides a solution to many of the problems that a web programmer encounters on a daily basis.

Let's imagine a situation where a file needs to be read character by character. For this we can use the function fgetc ()... The function takes a single parameter. The function is useful if we need to find any character or the number of identical characters.

$ fp = fopen ("counter.txt", "r"); // Open the file in read mode
if ($ fp)
{
while (! feof ($ fp))
{
$ char = fgetc ($ fp);
if ($ char == "c") $ i = $ i + 1; // Find the character "c"
}
echo "Number of letters" c "in file:". $ i;
}
else echo "Error opening file";
?>

III... Closing the file

Closing the file using the function fclose () which takes 1 required parameter.

$ fp = fopen ("counter.txt", "r");
if ($ fp)
{
echo "File open";
fclose ($ fp); // Close the file
}
?>

Collection of recipes

1) We need to check if this or that file exists. To do this, we will use the function file_exists ().

myfile ("counter.txt"); // Use the myfile function, passing the filename as an argument

function myfile ($ name) // Create a function to check if a file exists
{
if (file_exists ($ name)) echo "File exists";

}
?>

Note: Function file_exists does not check files on the remote web server. For correct work functions, the script file must be located on the server where the file being checked is.

2) Determine the file size using the function filesize()

myfile ("counter.txt");

function myfile ($ name) // Create a function to check for the existence of a file and determine the size of the file
{
if (file_exists ($ name)) echo "File size:" .filesize ($ name). "byte";
else echo "File does not exist";
}
?>

3) Create a temporary file using a function tmpfile()

$ myfile = tmpfile ();
fwrite ($ myfile, "This line is written to a temporary file."); // Write to a temporary file
fseek ($ myfile, 0); // Set the file pointer
echo fread ($ myfile, 1024); // display the contents of the file
?>

4) You need to define the number of lines in the file. For this we use the function count()

$ fp = file ("counter.txt");
echo "Number of lines in file:" .count ($ fp);
?>

5) We need to use the file locking mechanism

$ fp = fopen ("counter.txt", "a");
flock ($ fp, LOCK_EX); // Lock the file for writing
fwrite ($ fp, "String to write");
flock ($ fp, LOCK_UN); // Unlock
fclose ($ fp);
?>

6) We need to remove a specific line from the file

$ num_stroka = 5; // Remove line 5 from the file
$ file = file ("counter.txt"); // Read the entire file into an array

for ($ i = 0; $ i< sizeof($file); $i++)
if ($ i == $ num_stroka) unset ($ file [$ i]);

$ fp = fopen ("counter.txt", "w");
fputs ($ fp, implode ("", $ file));
fclose ($ fp);
?>

7) Determining the file type. We use the function