How to read files correctly using PHP. Working with the file system

In PHP, you often have to deal with creating a file... it's very simple: there is no file on disk, the code was run 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 that in this article...

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

Let's take a look at an example:

$text = "Some kind of text 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 writing and clarifications;

This clarification (the mode parameter of the fopen function) is very important:

  • "r" - open a file in php Only for reading. The cursor is placed at the beginning.
  • "r+" - open a file in php for reading and 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 appear 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. What is needed is written and the Cursor is placed at the beginning.
  • "w+" - opens a file for writing AND READING! The rest is the same as in the "w" mode. !!! - in these two modes - if the file has not been created - AN ATTEMPT WILL BE MADE TO CREATE IT!
  • "a" - open the file ONLY for writing. Unlike "w", this option does not overwrite the contents of the file, but places the cursor at the end of the line and appends the content that we wanted to add to the end.
  • "a+" - open the file for writing and reading.

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

fclose($fp) - function for closing the file that we wrote to the $fp variable;

Now you can easily create files in php correctly, open them for reading and editing.

Useful PHP additions 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, do this” 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 place a tag

This string function fgets(resource handle [, int length]) by default accepts 1024 bytes (1 kilobyte) as the length parameter, if not specified it will be so. This parameter is optional as of PHP 4.2.0 (Returns FALSE in case of 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 returns the number of bytes output. In case of an error, it will return if the dog is not used - @readfile.

Something like this will happen:

At the end of the word there is a tag
.

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 an array:

This way you can read any pages on the Internet: $lines = file("http://site/"); and iterate through the array using 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 contents as a single string.

This is a more universal PHP function for reading a file, similar to the file function, only the contents are returned as a string, not an array, and you can set conditions - which byte to start with - offset and where to end - maxlen. On failure, it will return FALSE.

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

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

In fact, how to open a php file is not a big problem. It can be harder to open a bottle of beer when you're in the middle of a forest. But only avid programmers think this way. And for beginners, we’ll tell you about all the capabilities of PHP for working with files:

php files

Files with the php extension contain code written in the programming language of the same name. Unlike other languages, php is a server-side programming language. That is, it runs on the server side. Therefore, to debug its code, a local server must be installed on the client machine.

To work with php files, special applications are used - software editors. The most common ones are:

  • Dreamweaver.
  • PHPEdit.
  • Eclipse PHP Development.


When creating websites based on PHP, you may need to reuse program code. In such situations, it is convenient to connect ready-made solutions located in another file. The include construct is used for this. Its syntax is:

include filename

Connection example:

Included file:


Including a file is also possible using the require construct. Unlike include, it includes the file before the program code is executed. Using require in the code, only one call to this file is possible. When accessed again, the system will display a global error message and stop program execution.

The include construct only includes the source during program execution. It supports multiple reading of php file. If an error occurs, only a warning message will be displayed, and code execution will continue from the next line.



Opening and closing files

In php, all operations with files are carried out in several stages:

  • Opening a file;
  • Content editing;
  • Closing the file.

The fopen() function is used to open a file. Its syntax is:

int fopen(string filename, string mode [, int use_include_path])

Accepted arguments:

  • string filename – file name or absolute path to it. If the path to the file is not specified, it will be searched in the current directory. If the file you are looking for is missing, the system will display an error message. Example:


  • string mode – indicates the file opening mode. Values ​​accepted by the argument:
  • r – the file is opened for reading only, the file pointer is set at the beginning;
  • r+ – file is open for reading and writing;
  • w – creates a new file for writing only. If a file with the same name already exists, all data in it is automatically deleted;
  • w+ - creates a new file for writing and reading. When such a file exists, its data is completely overwritten with new ones;
  • a – the file is open for writing. The pointer is set at the end. That is, writing to the php file will start not from the beginning, but from the end;
  • a+ – open a file in read-write mode. The recording will start from the end;
  • b – mode of working with a file containing binary data (in the binary number system). This mode is only available on the Windows operating system.

To close access to a file, use the fclose() function. Syntax:

int fclose (int file) , where int file is a handle to the site to be closed.

After each read or write, the file must be closed with this function. Otherwise, the stream created for the file remains open. And this leads to unnecessary consumption of server capacity.

Example:

Reading and writing files

To simply display the entire contents of a file, the readfile() function is ideal. Its syntax is:

readfile (string filename) , where string filename is the string file name (not a handle).


int fpassthru (int file)

The function requires opening and closing a file. Example:

The result is similar to the previous one.

Functions for working with files in php allow you to read content line by line and character by character:

  • string fgets (int file, int length)– the function reads a string of length length . Example:


  • string fread (int file, int length)– the action is identical to the previous one.

To write text data to a file, there are two identical functions:

  • int fputs (int file, string string [, int length ])
  • int fwrite(int file, string string [, int length ])

The functions write to a file int file a string string of the specified length int length ( optional argument). Example:


Creating and deleting files

To create a php file, you can use the fopen() function in "w" or "w+" access mode. Or the touch() function. It sets the modification time of the file. If there is no element with the searched name, it will be created. Its syntax is:

int touch (string filename [, int time [, int atime]])

To create a copy of a file, use the copy() function. As arguments, it takes the name of the original and the file where the contents should be copied. If it does not exist, it will be created. Function syntax:

int copy(string file1, string file2)


You can delete a file using the unlink() function. Its syntax.

Before attempting to work with a file, it is advisable to ensure that it exists. To solve this problem, two functions are usually used:

file_exists() and is_file().

The file_exists() function checks whether a given file exists. If the file exists, the function returns TRUE, otherwise it returns FALSE. The file_exists() function syntax is:

bool file_exists(string file)

An example of checking the existence of a file:

if (!file_exists($filename)) :

print "File $filename does not exist!";

is_file()

The is_file() function checks the existence of a given file and the ability to perform read/write operations on it. Essentially, is_file() is a more robust version of file_exists() that checks not only whether a file exists, but also whether it can read and write data:

bool is_file(string file)

The following example shows how to verify that a file exists and that operations can be performed on it:

$file = "somefile.txt";

if (is_file($file)) :

print "The file $file is valid and exists!";

print "The file $file does not exist or it is not a valid file!";

After making sure that the desired file exists and that various read/write operations can be performed with it, you can proceed to the next step - opening the file.

The filesize() function returns the size (in bytes) of the file with the given name, or FALSE on error. Filesize() function syntax:

int filesize(string filename)

Let's say you want to determine the size of the pastry.txt file. To obtain the necessary information, you can use the filesize() function:

$fs = filesize("pastry.txt"); print "Pastry.txt is $fs bytes.";

The following result is displayed:

Pastry.txt is 179 bytes.

Before you can perform operations on a file, you must open it and associate it with a file handler, and after you are done working with the file, you must close it. These topics are covered in the next section.

Opening and closing files

Before you can perform I/O on a file, you must open it using fopen().

The fopen() function opens a file (if it exists) and returns an integer -- called file manipulator(file handle). fopen() function syntax:

int fopen (string file, string mode [, int enable_path])

The file being opened can be on the local file system, exist as a standard input/output stream, or represent a file on a remote system accepted via HTTP or FTP.

The file parameter can be specified in several forms, listed below:

If the parameter contains the name of a local file, fopen() opens that file and returns a handle.

If the parameter is specified as php://stdin, php://stdout, or php://stderr, the corresponding standard input/output stream is opened.

If the parameter begins with the http:// prefix, the function opens an HTTP connection to the server and returns a handle for the specified file.

If the parameter begins with the ftp:// prefix, the function opens an FTP connection to the server and returns a handle for the specified file. There are two things to pay particular attention to in this case: If the server does not support passive FTP mode, the fopen() call will fail. Moreover, FTP files are opened either for reading or writing.

When operating in passive mode, the YAR server waits for connections from clients. When operating in active mode, the server itself establishes a connection with the client. The default is usually active mode.

The mode parameter determines the ability to read and write to the file. In table 7.1 lists some values ​​that determine the file opening mode.

Table 7.1. File opening modes

Mode Description
Only reading. The current position pointer is set to the beginning of the file
r+ Read and write. The current position pointer is set to the beginning of the file
w Recording only. The current position pointer is set to the beginning of the file, and the entire contents of the file are destroyed. If the file does not exist, the function tries to create it
w+ Read and write. The current position pointer is set to the beginning of the file, and the entire contents of the file are destroyed. If the file does not exist, the function tries to create it
a Recording only. The current position pointer is set to the end of the file. If the file does not exist, the function tries to create it
a+ Read and write. The current position pointer is set to the end of the file. If the file does not exist, the function tries to create it

If the optional third parameter include_path is 1, then the file path is relative to the include directory specified in the php.ini file (see Chapter 1).

Below is an example of opening a file using the fopen() function. The die() call, used in conjunction with fopen(), provides an error message if the file cannot be opened:

$file = "userdata.txt"; // Some file

$fh = fopen($file, "a+") or die("File ($file) does not exist!");

The following snippet opens a connection to the PHP site (http://www.php.net):

$site = "http://www.php.net": // Server accessible via HTTP

$sh = fopen($site., "r"); //Associate the manipulator with the Php.net index page

After finishing work, the file should always be closed using fclose().

The fclose() function closes a file with the given manipulator. If closing is successful, TRUE is returned; if closing is unsuccessful, FALSE is returned. fclose() function syntax:

int fclose(int manipulator)

The fclose() function successfully closes only those files that were previously opened by the fopen() or fsockopen() functions. Example of closing a file:

$file = "userdata.txt";

if (file_exists($file)) :

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

// Perform file operations

print "File Sfile does not exist!";

Write to file

There are two main operations performed on open files: reading and writing.

The is_writeable() function verifies that a file exists and is writeable. Writeability is checked for both the file and the directory. The is_writeable() function syntax is:

bool is_writeable (string file)

One important thing to note is that PHP will most likely run under the user ID used by the web server (usually "nobody"). An example of using is_writeable() is given in the description of the fwrite() function.

The fwrite() function writes the contents of a string variable to the file specified by the file handler. fwrite() function syntax:

int fwrite(int manipulator, string variable [, int length])

If the optional length parameter is passed when calling the function, writing stops either after writing the specified number of characters or when the end of the line is reached. Checking whether a file can be written to is demonstrated in the following example:

// Information about traffic on the user site

$data = "08:13:00|12:37:12|208.247.106.187|Win98";

$filename = "somefile.txt";

// If the file exists and can be written to

if (is_writeable($filename)) :

$fh = fopen($filename, "a+");

// Write the contents of $data to a file

$ success - fwrite($fh, $data);

// Close file

fclose($fh); else:

print "Could not open Sfilename for writing";

The fputs() function is an alias to fwrite() and can be used anywhere fwrite() is used.

The fputs() function is an alias to fwrite() and has exactly the same syntax. fputs() function syntax:

int fputs(int manipulator, string variable [, int length])

Personally, I prefer to use fputs(). It should be remembered that this is just a matter of style and has nothing to do with any differences between the two functions.

Reading from a file

Undoubtedly, reading is the most important operation performed on files. Below are some features that make reading from a file more efficient. The syntax of these functions almost exactly copies the syntax of similar recording functions.

The i s_readable() function allows you to verify that the file exists and is readable. Readability is checked for both the file and the directory. The is_readable() function syntax is:

boo! is_readable(string file]

Most likely, PHP will run under the user ID used by the web server (usually "nobody"), so for the is_readable() function to return TRUE, the file must be allowed to be read by everyone. The following example shows how to verify that a file exists and is readable:

if (is_readable($filename)) :

// Open the file and set the current position pointer to the end of the file

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

print "$filename is not readable!";

The fread() function reads the specified number of bytes from a file specified by the file manipulator. fwrite() function syntax:

int fread(int manipulator, int length)

The manipulator must refer to an open file that is readable (see the description of the is_readable() function). Reading stops after a specified number of bytes have been read or when the end of the file is reached. Consider the text file pastry.txt shown in Listing 7.1. Reading and output of this file in the browser is carried out by the following fragment:

$fh = fopen("pastry.txt", "r") or die("Can"t open file!");

$file = fread($fh, filesize($fh));

By using the fllesize() function to determine the size of pastry.txt in bytes, you ensure that the fread() function reads the entire contents of the file.

Listing 7.1. Text file pastry.txt

Recipe: Pastry Dough

1 1/4 cups all-purpose flour

3/4 stick (6 tablespoons) unsalted butter, chopped

2 tablespoons vegetable shortening 1/4 teaspoon salt

3 tablespoons water

The fgetc() function returns a string containing one character from the file at the current pointer position, or FALSE when the end of the file is reached. fgetc() function syntax:

string fgetc (int manipulator)

The manipulator must reference an open file that is readable (see the description of the is_readable() function earlier in this chapter). The following example demonstrates character-by-character reading and output of a file using the fgetc() function:

$fh = fopen("pastry.txt", "r"); while (!feof($fh)) :

$char = fgetc($fh):

print $char; endwhile;

The fgets() function returns a string read from the current pointer position in the file specified by the file handler. The file pointer must point to an open file that is readable (see the description of the is_readable() function earlier in this chapter). fgets() function syntax:

string fgets (int manipulator, int length)

Reading stops when one of the following conditions is met:

  • read from file length -- 1 byte;
  • a newline character was read from the file (included in the returned string);
  • The end of file (EOF) flag has been read from the file.

If you want to organize line-by-line reading of a file, pass in the second parameter a value that is obviously greater than the number of bytes in the line. Example of line-by-line reading and output of a file:

$fh = fopen("pastry.txt", "r");

while (!feof($fh));

$line = fgets($fh, 4096);

print $line. "
";

The fgetss() function is completely similar to fgets() with one exception - it attempts to remove all HTML and PHP tags from the read text:

string fgetss (Int manipulator, int length [, string allowed_tags])

Before moving on to the examples, review the contents of Listing 7.2—this file is used in Listings 7.3 and 7.4.

Listing 7.2. File science.html

Breaking News - Science

Alien lifeform discovered


August 20. 2000

Early this morning, a strange new form of fungus was found growing in the closet of W. J. Gilmore's old apartment refrigerator. It is not known if powerful radiation emanating from the tenant's computer monitor aided in this evolution.

Listing 7.3. Removing tags from an HTML file before displaying in the browser

$fh = fopen("science.html", "r");

while (!feof($fh)) :

print fgetss($fh, 2048);

The result is shown below. As you can see, all HTML tags have been removed from the science.html file, causing formatting to be lost:

In some situations, all but a few tags are removed from a file - for example, line break tags
. Listing 7.4 shows how this is done.

Listing 7.4. Selectively removing tags from an HTML file

$fh = fopenC"science.html", "r");

$allowable = "
";

while (!feof($fh)) :

print fgetss($fh. 2048, $allowable);

Result:

Breaking News - Science Alien lifeform discovered August 20. 2000 Early this morning, a strange new form of fungus was found growing in the closet of W. J. Gilmore's old apartment refrigerator. It is not known if powerful radiation emanating from the tenant's computer monitor aided in this evolution.

As you can see, the fgetss() function makes file conversion easy, especially when you have a large number of similarly formatted HTML files.

Reading a file into an array

The file() function loads the entire contents of a file into an indexable array. Each element of the array corresponds to one line of the file. File() function syntax:

array file (string file [, int include_path])

If the optional third parameter include_path is 1, then the file path is relative to the include directory specified in the php.ini file (see Chapter 1). Listing 7.5 uses the file() function to load the pastry.txt file (see Listing 7.1).

$file_array = file("pastry.txt");

while (list($line_num. $line) = eacht($file_array)):

print " Line $line_num:", htmlspecialchars($line), "
\n"

Each row of the array is printed along with a number:

Line 0: Recipe: Pastry Dough

Line 1: 1 1/4 cups all-purpose flour

Line 2: 3/4 stick (6 tablespoons) unsalted butter, chopped

Line 3: 2 tablespoons vegetable shortening

Line 4: 1/4 teaspoon salt

Line 5: 3 tablespoons water

Redirecting a file to standard output

The readfile() function reads the contents of a file and writes it to standard output (in most cases, to the browser). readfile() function syntax:

int readfile (string file [, int include_path])

The function returns the number of bytes read. The file can reside on the local file system, exist as standard input/output, or represent the file on a remote system accepted via HTTP or FTP. The file parameter is set according to the same rules as in the fopen() function.

Let's say you have a file latorre.txt, the contents of which you want to display in the browser:

Restaurant "La Torre." located in Nettuno, Italy, offers an eclectic blend of style. history, and fine seafood cuisine. Within the walls of the medieval borgo surrounding the city, one can dine while watching the passersby shop in the village boutiques. Comfort coupled with only the freshest seafare make La Torre one of Italy's finest restaurants.

When the following snippet is executed, the entire contents of latorre.txt are sent to standard output:

$restaurant_file = "latorre.txt";

// Send the entire file to standard output

readfile($restaurant_file);

Opening a process file handler

Along with regular files, you can open file manipulators to interact with processes on the server. The problem is solved by the popen() function, which has the following syntax:

int popen (string command, string mode)

The command parameter specifies the system command to be executed, and the mode parameter describes the access mode:

// Open the file "spices.txt" for writing

$fh = fopen("spices.txt","w");

// Add some lines of text

fputs($fh, "Parsley, sage, rosemary\n");

fputs($fh, "Paprika, salt, pepper\n");

fputs($fh, "Basil, sage, ginger\n");

// Close the manipulator

// Open a UNIX grep process to search for the word Basil in the spices.txt file

$fh - popen("grep Basil< spices.txt", "r");

// Print the result of grep

The result looks like this:

Basil, sage, ginger

The fpassthru() function is similar to the passthru() function discussed in the “Running External Programs” section of this chapter.

After completing all operations, the file or process must be closed. The pclose() function closes the connection to the process specified by the manipulator, similar to the way the fclose() function closes a file opened by the fopen() function. pclose() function syntax:

int pclose (int manipulator)

In the parameter manipulator the manipulator received earlier with a successful call to popen() is transmitted.

Opening a socket connection

PHP isn't limited to interacting with files and processes—you can also make connections via sockets. Socket A socket is a software abstraction that allows you to communicate with various services on another computer.

The fsockopen() function establishes a socket connection to a server on the Internet

via TCP or UDP protocol. fsockopen() function syntax:

int fsockopen (string node, int port [, int error_code [, string error_text [, int timeout]]])

The optional parameters error_code and error_text contain information that will be displayed if the connection to the server fails. Both parameters must be passed by reference. The third optional parameter, timeout, specifies the length of time to wait for a response from the server (in seconds). Listing 7.6 demonstrates using the fsockopen() function to obtain server information. However, before looking at Listing 7.6, there's one more function you need to know: socket_set_blocking().

UDP (User Datagram Protocol) is a connectionless communication protocol.

socket_set_blocking()

The socket_set_b1ocki ng() function allows you to set timeout control for server operations:

socket_set_blocking(int manipulator, boolean mode)

The manipulator parameter specifies the previously opened socket, and the mode parameter selects the mode the socket is switched to (TRUE for blocking mode, FALSE for non-blocking mode). An example of using the fsockopen() and socket_set_blocking() functions is shown in Listing 7.6.

Listing 7.6. Using fsockopen() to get server information

function getthehost($host.$path) (

// Open a connection to the node

$fp - fsockopen($host, 80, &$errno, &$errstr, 30);

// Go to blocking mode

socket_set_blocking($fp, 1),

// Send headers

fputs($fp,"GET $path HTTP/1.1\r\n");

fputs($fp, "Host: $host\r\n\r\n"); $x = 1;

// Get headers

while($x< 10) :

$headers = fgets($fp, 4096);

// Close the manipulator

getthehost("www. apress.com", "/");

Running Listing 7.6 produces the following output:

HTTP/1.1 200 OK Server: Microsoft-IIS/4.0 Content-location:

2000 20:25:06 GMT ETag: "f0a61666dbff1bf1:34a5" Content-Length: 1311

The pfsockopen() function is a persistent version of fsockopen(). This means that the connection will not be automatically closed when the script in which the function was called ends. The pfsockopen() function syntax is:

int pfsockopen (string node, int port [, int error_code [, string error_text [, int timeout]]])

Depending on the specific goals of your application, you may find it more convenient to use pfsockopen() instead of fsockopen().

Launching external programs

PHP scripts can also execute programs located on the server. This feature is especially often used when administering the system via a web browser, as well as for more conveniently obtaining summary information about the system.

The exec() function runs a given program and returns the last line of its output. Syntax of the exec() function:

string exec (string command [, string array [, int return]])

Please note that the exec() function only executes the command and does not print its results. All command output can be stored in an optional array parameter. Additionally, if a return variable is also specified when the array parameter is specified, the latter is assigned the return code of the executed command.

Listing 7.7 shows how to use the exec() function to execute the UNIX ping system function.

Listing 7.7. Checking connection with the server using the exec() function

exec("ping -from 5 www.php.net", $ping);

// On Windows - exec("ping -n 5 www.php.net. $ping);

for ($i=0; $i< count($ping);$i++) :

print "
$ping[$i]";

Result:

PING www.php.net (208.247.106.187): 56 data bytes

64 bytes from 208.247.106.187: icmp_seq=0 ttl=243 time=66.602 ms

64 bytes from 208.247.106.187: icmp_seq=1 ttl=243 time=55.723 ms

64 bytes from 208.247.106.187: icmp_seq=2 ttl=243 time=70.779 ms

64 bytes from 208.247.106.187: icmp_seq=3 ttl=243 time=55.339 ms

64 bytes from 208.247.106.187: icmp_seq=4 ttl=243 time=69.865 ms

www.php.net ping statistics --

5 packets transmitted. 5 packets received. 0% packet loss

round-trip min/avg/max/stddev - 55.339/63.662/70.779/6.783 ms

Back apostrophes

There is another way to execute system commands that does not require calling functions - the command being executed is enclosed in backticks (` `), and the results of its operation are displayed in the browser. Example:

print "

$output
";

This snippet displays the contents of the directory where the script is located in the browser.

The internal parameter ping -c 5 (-p 5 on Windows) specifies the number of server polls.

If you just want to return the unformatted results of a command, use the passthru() function described below.

The passthru() function works much the same as exec(), with one exception - it automatically prints the results of the command. The passthru() function syntax is:

void passthru(string command [, int return])

If an optional return parameter is passed when calling passthru(), this variable is set to the return code of the executed command.

escapeshellcmd()

The escapeshellcmd() function escapes any potentially dangerous characters that might be entered by the user (for example, on an HTML form) to execute the exec(), passthru(), system(), or popen() commands. Syntax:

string escapeshellcmd (string command)

User input should always be treated with some caution, but even so, users can enter commands that will be executed by system command functions. Consider the following snippet:

$user_input = `rm -rf *`; // Delete the parent directory and all its subdirectories

exec($user_input); // Execute $user_input !!!

If no precautions are taken, such a command will lead to disaster. However, you can use the escapeshellcmd() functions to escape user input:

$user_input = `rm - rf *`; // Delete the parent directory and all its subdirectories

ex(escapeshellcmd($user_input)); // Escape dangerous characters

The escapeshellcmd() function escapes the * character, preventing the command from having catastrophic consequences.

Security is one of the most important aspects of Web programming, so I devoted an entire chapter to this topic and how it relates to PHP programming. See Chapter 16 for more information.

Working with the file system

PHP has functions for viewing and performing various operations on files on the server. Information about server file attributes (location, owner, and privileges) is often useful.

The basename() function extracts the file name from the passed full name. Basename() function syntax:

string basename(string full_name)

Extracting the base file name from the full name is done as follows:

$path = "/usr/local/phppower/htdocs/index.php"; $file = basename($path); // $file = "index.php"

In effect, this function removes the path from the full name and leaves only the file name.

The getlastmod() function returns the date and time of the last modification of the page from which the function is called. getlastmod() function syntax:

int getlastmod(void)

The return value follows the UNIX date/time format, and you can use the date() function to format it. The following snippet displays the date the page was last modified:

echo "Last modified: ".date("H:i:s a". getlastmod());

The stat() function returns an indexable array with detailed information about the file with the given name:

array stat(string filename)

The following information is returned in the array elements:

0 Device

2 Index node protection mode

3 Number of links

4 Owner user ID

5 Owner group ID

6 Index node device type

7 Size in bytes

8 Time of last call

9 Time of last modification

10 Last modified time

11 Block size for file system I/O

12 Number of allocated blocks

Thus, if you want to know the last time a file was accessed, look at element 8 of the returned array. Let's look at an example:

$file - "datafile.txt";

list($dev, $inode, $inodep, $nlink, $uid, $gid, $inodev, $size, $atime, $mtime, $ctime,

$bsize) = stat($file);

print "$file is $size bytes.
";

print "Last access time: $atime
";

print "Last modification time: $mtime
";

Result:

popen.php is 289 bytes.

Last access time: August 15 2000 12:00:00

Last modification time: August 15 2000 10:07:18

In this example, I used the list() construct to assign names to each return value. Of course, you can just as easily return an array, loop through the elements and display all the necessary information. As you can see, the stat() function allows you to get various useful information about a file.

Displaying and changing file characteristics

Each file on UNIX family systems has three important characteristics:

  • belonging to a group;
  • owner;
  • permissions.

All these characteristics can be changed using the appropriate PHP functions. The features described in this section do not work on Windows family systems.

If you do not have experience with UNIX operating systems, information about the characteristics of the UNIX file system can be found at http://sunsite.auc.dk/linux-newbie/FAQ2.htm. The topics of group membership, ownership, and permissions are discussed in Section 3.2.6.

The chgrp() function attempts to change the group to which a given file belongs. chgrp() function syntax:

int chgrp (string filename, mixed group)

The filegroup() function returns the group ID of the owner of the file with the given name, or FALSE on error. Filegroup() function syntax:

int filegroup (string filename)

The chmod() function changes the permissions of a file with the given name. chmod() function syntax:

int chmod (string filename, int permissions)

Permissions are specified in octal notation. The specifics of setting a parameter to the chmod() function are demonstrated in the following example:

chmod("data_file.txt", g+r); // Doesn't work

chmod("data_file.txt", 766); // Does not work

chmod("data_file.txt", 0766); // Works

The fileperms() function returns the permissions of the file with the given name, or FALSE on error. Fileperms() function syntax:

int fileperms (string filename)

The chown() function attempts to change the owner of a file. The right to change the owner of a file is limited to the privileged user. chown() function syntax:

int chown (string filename, mixed user)

The fileowner() function returns the user ID for the owner of the file with the given name. Fileowner() function syntax:

int fileowner (string filename)

Copying and renaming files

Other useful system functions that can be performed in PHP scripts include copying and renaming files on the server. These operations are performed by two functions: copy() and rename().

Copying a file in a PHP script is no more difficult than using the UNIX cf command. The problem is solved by the PHP function copy(). The syntax of the soru() function is:

int copy (string source, string destination)

The function copy() tries to copy the source file to the destination file; TRUE is returned on success, FALSE on failure. If the destination file does not exist, the copy() function creates it. The following example shows how to create a backup copy of a file using the copy() function:

$data_file = "data.txt";

copy($data_file. $data_file".bak") or die("Could not copy $data_file");

The rename() function renames a file. If successful, TRUE is returned, and if unsuccessful, FALSE is returned. Rename() function syntax:

bool rename (string old_name, string new_name)

An example of renaming a file using the rename() function:

$data_file = "data.txt";

rename($data file, $datafile".old") or die("Could not rename $data file");

Deleting files

The unlink() function deletes a file with the given name. Syntax:

int unlink (string file)

If you are working with PHP on a Windows system, you may sometimes experience problems using this feature. In this case, you can use the system() function described above and delete the file with the DOS del command:

system("del filename.txt");

Working with catalogs

PHP functions allow you to view and navigate the contents of directories. Listing 7.8 shows a typical directory structure on a UNIX system.

Listing 7.8. Typical directory structure

The dirname() function complements basename() - it extracts the path from the fully qualified file name. The syntax of the dirname() function is:

string dirname (string path)

An example of using dirname() to extract a path from a full name:

$path = "/usr/locla/phppower/htdocs/index.php";

$file = dirname($path); // $file = "usr/local/phppower/htdocs"

The dirname() function is sometimes used in conjunction with the $SCRIPT_FILENAME variable to obtain the full path to the script from which the command is executed:

$dir - dirname($SCRIPT_FILENAME);

The is_dir() function checks whether a file with a given name is a directory:

bool is_dir (string filename)

The following example uses the directory structure from Listing 7.8:

$ isdir = is_dir("index.html"); // Returns FALSE

$isdir = is_dir("book"); // Returns TRUE

The mkdir() function does the same thing as the UNIX command of the same name - it creates a new directory. mkdir() function syntax:

int mkdir (string path, int mode)

The path parameter specifies the path to create the new directory. Don't forget to end the parameter with the name of the new directory! The mode parameter determines the permissions assigned to the created directory.

Just as the fopen() function opens a manipulator to work with a given file, the opendir() function opens a manipulator to work with a directory. The syntax of the opendir() function is:

int opendir (string path)

The closedir() function closes the directory handle passed as a parameter. The closedir() function syntax is:

void closedir(int directory_manipulator)

The readdir() function returns the next element of the specified directory. Syntax:

string readdir(int directory_manipulator)

Using this function, you can easily list all files and subdirectories located in the current directory:

$dh = opendir(" .);

while ($file = readdir($dh)) :

print "$file
"; endwhile;

The chdir() function works just like the UNIX cd command; it changes to the directory specified by the parameter. chdir() function syntax:

int chdir (string directory)

In the following example, we navigate to the book/ subdirectory and print its contents:

$newdir = "book";

chdir($newdir) or die("Could not change to directory ($newdir)"); $dh = opendir(" . ");

while ($file = readdir($dh)) ;

print "$file
";

The rewlnddir() function moves the current position pointer to the beginning of the directory opened by the opendir() function. The rewinddir() function syntax is:

void rewinddir (int directory_manipulator)

Project 1: Simple hit counter

The script presented in this section counts the number of hits to the page it is on. Before moving on to the code in Listing 7.9, review the algorithm written in pseudocode:

  1. Assign the $access variable the name of the file in which the counter value will be stored.
  2. Use the file() function to read the contents of $access into the $visits array. The @ prefix before the function name suppresses possible errors (for example, there is no file with the given name).
  3. Set the $current_visitors variable to the value of the first (and only) element of the $visits array.
  4. Increase $current_visitors value by 1.
  5. Open the $access file for writing and set the current position pointer to the beginning of the file.
  6. Write the $current_visitors value to the $access file.
  7. Close the manipulator that references the $access file.

Listing 7.9. Simple hit counter

// Script: simple hit counter

// Purpose: saving the number of hits in a file

$access = "hits.txt"; // The file name is chosen arbitrarily

$current_visitors = $visits; // Retrieve the first (and only) element

+$current_visitors; // Increase the hit counter

$fh = fopen($access. "w"); // Open the hits.txt file and install

// pointer to the current position at the beginning of the file

@fwrite($fh, $current_visitors);// Write a new counter value

// to the file "hits.txt"

fclose($fh); // Close file manipulator "hits.txt"

Project 2: building a site map

The script in Listing 7.10 builds a sitemap, a hierarchical view of all the folders and files on the server, starting at a given directory. Calculating the padding of the elements that make up a sitemap uses the functions defined in this and previous chapters. Before moving on to the program, review the algorithm written in pseudocode:

  1. Declare service variables to store the parent directory, the name of the graphic file with the image of the folder, the page name and the server OS flag (Windows or another system).
  2. Declare a display_directory() function that reads the contents of a directory and formats it for display in the browser.
  3. Construct the directory path by combining the name passed in the $dir1 variable with $dir.
  4. Open a directory and read its contents. Format directory and file names and display them in the browser.
  5. If the current file is a directory, call display_di rectory() recursively and pass it the name of the new directory to display. Calculate the indentation used when formatting the output.

If the file is not a directory, it is formatted to display as a hyperlink (and the indentation used in formatting is also calculated).

Listing 7.10. Sitemap.php program

// File: sitemap.php

// Purpose: building a site map

// Directory from which map construction begins

$beg_path = "C:\Program FilesVApache Group\Apache\htdocs\phprecipes";

// File with a graphic image of the folder.

// The path must be Relative* to the root directory of the Apache server

$folder_location = "C:\My Documents\PHP for Programmers\FINAL CHPS\graphics\folder.gif";

// Text in the window title $page_name = "PHPRecipes SiteMap";

// On which system will the script be used - Linux or Windows?

// (0 - Windows; 1 - Linux)

$usingjinux = 0;

// Function: display_directory

// Purpose: reading the contents of the directory specified by the parameter

// $dir1, followed by formatting of the directory and file hierarchy.

// The function can be called recursively.

function display_directory ($dir1, $folder_location, $using_linux, $init_depth) (

// Update path

Sdh = opendir($dir);

while($file = readdir($dh)) :

// Directory elements "." and ".." are not output.

if (($file != ".") && ($file != "..")) :

if ($using_linux == 0) :

$depth = explode("\\", $dir): else:

$depth = explode("/", $dir); endif ; $curtent_depth = sizeof($depth);

// Build the path according to the rules of the operating system used. if ($using_linux == 0) :

$tab_depth = $current_deptn - $init_depth;

$file = $dir. "\\", $file; else:

$file = $dir. "/",$file; endif;

// Does $file contain a directory? if (is dir($file)) :

// Calculate indentation

while ($x< ($tab_depth * 2)) :

$x++; endwhile;

print "

".basename($file)."
";

// Increment counter

// Recursive call to display_directory()

display_directory($file, $folder_location, $using_linux, $init_depth);

// Not a directory

// Build a path according to the rules of the used

// operating system.

if ($using_linux == 0) :

$tab_depth = ($current_depth - $init_depth) - 2; $x = 0;

// Calculate indentation

while ($x< (($tab_depth * 2) + 5)) :

print " ".basename($file)."
";

print " ".basename($file)."
";

endif; // Is_dir(file) endif: // If ! "." or ".."

// Close the directory closedir($dh);

<? print "$page_name"; ?>

// Calculate initial padding

if ($using_linux == 0) :

$depth = explode("\\", $beg_path);

$depth = explode("/", $beg_path);

$init_depth = sizeof($depth);

display_directory($beg_path, $folder_location, $using_linux, $init_depth);

In Fig. Figure 7.1 shows the result of running the script against a directory containing several chapters of this book.

Rice. 7.1. Outputting the directory structure on the server using the sitemap.php script

Results

This chapter introduced many of PHP's tools for working with files. In particular, we considered the following issues:

  • checking the existence of files;
  • opening and closing files and I/O streams;
  • writing to and reading from a file;
  • redirecting the file to the output stream;
  • launching external programs;
  • file system operations.

The material in this chapter sets the stage for the next chapter, “Strings and Regular Expressions,” because when developing web applications, string processing and I/O operations are very closely related.

About using the functions fopen, fclose, feof, fgets, fgetss, and fscanf

Let's list all the possibilities

One of the benefits of working with modern programming languages ​​like PHP is the number of features available. PHP could easily adopt Perl's motto, "There's more than one way to do something," especially when it comes to file processing. But with the plethora of tools available, the question becomes which one is best for getting the job done. Of course, the answer to this question really depends on what your goals are when processing the file, so learning all the language's capabilities is worth your time.

Traditional fopen methods

The fopen methods are probably the most familiar to C and C++ programmers of yore, as they are more or less the tools that have been at your fingertips for years if you've worked with those programming languages. For any of these methods, you follow the 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 using fgets
$file_handle = fopen("myfile", "r"); while (!feof($file_handle)) ( $line = fgets($file_handle); echo $line; ) fclose($file_handle);

Although 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 each line you read.
  4. Close the file.

With that in mind, I'll look at each file function used here.

fopen function

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

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

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

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

feof function

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

Function fclose

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

fgets function

Going back a few lines in Listing 1, you get to the heart of the file processing process: actually 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 display the data or otherwise process it. The example in Listing 1 prints the entire file.

If you decide to limit the size of the data chunk you work with, you can add an fgets argument to limit the maximum length of the data string that is captured. For example, use the following code to limit the length of a line to 80 characters:

$string = fgets($file_handle, 81);

Think of "\0", the end-of-line indicator in C, and set the length to one character longer 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 line length limit for a given function.

fread function

The fgets function is just one of many functions available for reading a file. This is one of the most commonly used functions, since processing a file line by line in most cases makes the most sense. In fact, several other features offer similar capabilities. Be that as it may, line-by-line analysis is not always what you need.

And here we access fread. The fread function has a slightly different purpose than fgets: it is intended to read from binary files (that is, files that do not initially consist of human-readable text). Since the concept of "lines" is not relevant for binary files (logical data structures are not typically broken into lines), you must specify the number of bytes to be read.

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

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

Assuming the file is no larger than 8 KB, the program snippet below should read the entire file in one line.

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

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

fscanf function

Getting back to string processing, fscanf is also the successor to the traditional C file library function. If you're not familiar with it, fscanf reads data fields into variables from a file.

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

The format strings used in this function are described 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 the variable returned by the function. (In C, these would be passed as arguments.)

fgetss function

The fgetss function is different from traditional file manipulation functions and gives you a better understanding of PHP's capabilities. It works like fgets, but discards any HTML or PHP tags it detects, leaving only the bare text. Let's take the HTML file below.

Listing 2. Example 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 pass 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);

This is what you will 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 data from a file, you can print the remaining data using the standard output channel using the fpassthru function.

fpassthru($fh);

This function prints the data so you don't have to put it in a variable.

Non-linear file processing: moving through a file

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

fseek($fh, 0);

The example above goes 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 enough - you simply write:

fseek($fh, 1024);

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

fseek($fh, 100, SEEK_CUR);

Similarly, going back 100 bytes is done by:

fseek($fh, -100, SEEK_CUR);

If you want to go back to the 100 byte position before the end of the file, use SEEK_END instead.

fseek($fh, -100, SEEK_END);

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

Note: you cannot use fseek on file descriptors referencing a URL.

Capture an entire file

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

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

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

echo file_get_contents("myfilename");

This article primarily focuses on processing 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 might be looking at these examples and thinking, "That's a lot of work." PHP developers agree with you. So you can shorten the above command to:

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

The readfile function outputs the entire contents of a file or Web page to the default output buffer. By default, this command displays an error message when it fails. 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 single line returned by file_get_contents is probably too much. You might want to first split it into pieces using the split() function.

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

But why do you need all this complexity if there is a perfectly suitable function that will do the job for you? The PHP file() function accomplishes this task in one step: it returns a string array whose elements are the lines 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, whereas the file command ends the array lines with newlines (as does fgets).

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

Listing 4. 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 the array:

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

The result will be the following output:

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

Of course, you may notice that this command has merged the sections. This is the default action, but you can easily customize it by using the second argument of 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 puts data into an easily parsable multidimensional array.

But this is just the tip of the iceberg when it comes to file processing in PHP. More complex functions such as tidy_parse_file and xml_parse can help you parse HTML and XML documents, respectively. Refer to the section for more detailed information on how these functions work. Both of these are worth considering if you'll be working with these file types, but instead of going through all the possible file types, you might want to take a closer look at the contents of this article, which has some good general rules for working with the functions I've 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 a permission change causes you to be unable to read the contents of a file? You can check the existence of a file and the rights to read it in advance 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 program will probably be overkill 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 if it fails, this will ensure that the file will only be processed if the file can be opened. Of course, if the file doesn't exist or is unreadable, you'd expect the return value to be negative. Therefore, such a check is a trap into which all potential problems fall. Alternatively, you can exit the program 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 if an error occurs. Of course, with the exception of fclose , you've probably already processed the results they return. As for fclose , there's not much that can be done if the file handle doesn't close properly, so checking the return value of fclose is generally overkill.

The choice is yours

PHP has no shortage of efficient ways to read and parse files. Classic functions like fread may serve you reliably most of the time, or you may be more attracted to the simplicity of readfile if that's what you need to get the job done. The choice really depends on what you are trying to accomplish.

If you're processing large amounts of data, you'll probably find fscanf more useful and efficient than, say, using file in combination with the subsequent split and sprintf commands. If you are simply displaying a large amount of text with minor changes, however, using the file , file_get_contents , or readfile functions may make more sense. This solution will probably be correct when using PHP for caching or even creating a temporary proxy server.

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

PHP - Working with files

Every programmer should be able to work with files correctly. This article is aimed at beginner PHP programmers, but the “collection of recipes” will also be useful for advanced users.

Working with files is divided into 3 stages:

  • Opening a file.
  • Data manipulation.
  • Closing the file.

I. Opening a file

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

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

  • r – open the file for read-only.
  • r+ - opens a file for reading and writing at the same time.
  • w – creates a new empty file. If such a file already exists at the time of the call, it is destroyed.
  • w+ - similar to r+, only if the file exists at the time of calling, its contents are deleted.
  • a – opens an existing file in write mode, with the pointer shifted to the last byte of the file (to the end of the file).
  • a+ - opens a file in read-write mode, with the pointer shifted to the last byte of the file (to the end of the file). The contents of the file are not deleted.

Note: There may be one more optional parameter at the end of any of the lines: b or t. If b is specified, 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.

To demonstrate, consider the following scenario:

//Opens a 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 an FTP connection indicating the login and password

II. File Data Manipulation

You can write data to a file using PHP using the fwrite() function. This function takes 2 required parameters and 1 optional one. The required parameters are the file descriptor and the 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 was successfully entered into the file.";

Else

Echo "Error writing to file.";

Fclose($fp); //Close the file

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

If ($fp)

While (!feof($fp))

$mytext = fgets($fp, 999);

Echo $mytext."
";

Else

Fclose($fp);

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

Echo readfile("counter.txt");

You can also use the fpassthru() function which takes 1 required parameter. Before using this feature, 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);

Else

Echo "Error opening file";

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

Note: The file() function should not be used on binary files (binary-safe). It is not secure in terms of reading binary files, and if it encounters an end-of-file (EOF) character somewhere, it does not guarantee that you will read the entire binary file.

$file_array = file("counter.txt"); // Read the file into the $file_array

// Working with array data

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

At the end of the article, you will find a good "recipe book" on arrays, which provides solutions to many problems that a web programmer encounters every day.

Let's imagine a situation where a file needs to be read character by character. To do this, we can use the fgetc() function. 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 symbol “c”

Echo "Number of 'c' letters in file: ". $i;

Else echo "Error opening file";

III. Closing a file

The file is closed using the fclose() function, which takes 1 required parameter.

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

If ($fp)

Echo "File open";

Fclose($fp); // Closing the file

Collection of recipes

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

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

function myfile($name) //Create a function to check the existence of a file

If (file_exists($name)) echo "The file exists";

Note: The file_exists function does not check files on the remote web server. For the function to work correctly, the file with the script must be located on the same server as the file being checked.

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

myfile("counter.txt");

//Create a function to check the existence of a file and determine the file size

function myfile($name)

If (file_exists($name)) echo "File size: ".filesize($name)." bytes";

Else echo "The file does not exist";

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

$myfile = tmpfile();

// Write to a temporary file

Fwrite($myfile, "This line is written to a temporary file.");

Fseek($myfile, 0); // Set the file pointer

Echo fread($myfile, 1024); // output the contents of the file

4) You need to determine the number of lines in the file. To do this we use the count() function

$fp = file("counter.txt");

Echo "Number of lines in file: ".count($fp);

5) We need to use a 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 certain line from the file

$num_stroka = 5; //Delete 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 filetype() function, which takes a single parameter

$mytype = filetype("counter.txt");

Echo "File type: ".$mytype;

After the call, the string may contain one of the following values:

file – regular file

dir – directory

fifo – fifo channel

block – block-oriented device

char – character-oriented device

unknown – unknown file type

8) If you want to view all the parameters of a file, you should use the stat() function

$filename = stat("counter.txt");

Echo"

";

Print_r($filename);

Echo"

";

9) We need to clear the file, use the ftruncate() function

$fp = fopen("counter.txt", "a"); //Open the file in recording mode

Ftruncate($fp, 0) // clear the file

10) We need to find out the date of the last modification of the file, we use the filectime() function. The function returns a time value in Unix timestamp form.

Echo filectime("counter.txt");