How to read files properly with PHP. PHP: Reading a PHP file

16.5K

In fact, how to open a php file is not a big problem. It can be more difficult to open a bottle of beer when you are in the middle of a forest. But only avid programmers think so. And for beginners, let's talk about all the features 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 are used special applications- software editors. The most common of these are:

  • dreamweaver.
  • Edit.
  • Eclipse PHP Development.
When creating sites based on php, it may be necessary to reuse the program code. In such situations, it is convenient to include ready-made solutions located in another file. For this, the include construct is used. Its syntax is:

include filename

Connection example:

Connected file:


Attaching a file is also possible using require constructs. Unlike include, it includes a file even before the program code is executed. With the help of require in the code, only one call to this file is possible. Upon repeated access, the system will display a global error message and stop the program execution.

The include construct connects the source only 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 a 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 searched file does not exist, the system will display an error message. Example:

  • string mode - specifies the file opening mode. Values ​​accepted by the argument:
  • r - the file is open for reading only, the file pointer is set at the beginning;
  • r+ – the file is open for reading and writing;
  • w - Creates a new write-only file. If a file with the same name already exists, it automatically deletes all data;
  • w+ - creates a new file for writing and reading. If 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 not start from the beginning, but from the end;
  • a+ - open file in read-write mode. Recording will start from the end;
  • b – mode of working with a file containing binary data (in the binary system). This mode is only available in operating system Windows.

The fclose() function is used to close access to a file. 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 capacities.

Example:

Reading and writing files

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

readfile (string filename) , where string filename is a string filename (not a file descriptor).


The same file can be read using the fpassthru() function. It reads data from the end position of the pointer to the end of the file. Its syntax is:

int fpassthru (int file)

To work with the function, you need to open and close the file. Example:

The result is similar to the previous one.

The php file functions allow you to read the contents 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.

There are two identical functions for writing text data to a file:

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

The functions write to the file int file a string 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 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.

Last update: 1.11.2015

Like most programming languages, PHP supports files, which are one way to store information.

Reading and writing files

Opening and closing files

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

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

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

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

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

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

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

The result of the fopen function is a file descriptor. This handle is used for operations on the file and for closing it.

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

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

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

Reading a file

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

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

Reading the entire file

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

Block read

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

The fread() function takes two parameters: the file descriptor to read and the number of bytes to read. When reading a block, the pointer in the file moves to the end of this block. And also with the help of the feof () function, you can track the completion of the file.

Write file

To write a file, the fwrite() function is used, which writes a string to the file:

Another function fputs() works similarly:

Working with the file pointer

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

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

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

    SEEK_SET : default value, sets the offset to offset bytes from the beginning of the file

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

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

The fseek() function returns 0 if the pointer is successfully set, and -1 if it fails.

An example of using the function:

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

PHP appeared much later than programming languages ​​strengthened their positions, formulated general ideas about syntax, logic, variables and other program objects. Files and functions for working with them made no progress, and even the problem of file encoding, which arose for natural reasons, did not lead to radically new solutions.

General remarks

The basic work with files, whatever they are, is to open, read / write and close. You can use the functions of blocking / unblocking access to a file while it is being processed, you can set the read / write position in the file - everything, as before, is in the distant past.

An important point in PHP is the abundance of functions for working with files and their use cases. In practice, it is enough to apply simple, but working options. A file is, first of all, a program's memory. It can store information. The purpose of any program, the purpose of any site is to present, process and ensure the safety of information.

Essential circumstance

It used to be an unshakable requirement for compatibility at least from the bottom up. That is, once a program written in one version of the programming language is ideally compiled / interpreted in next version. This is not the case in modern programming. The requirement of compatibility of syntactic constructions of the language has gone down in history, and the struggle between styles and programming tools and versions of certain tools has become the norm of their life.

Working with files, like with databases, is as important as the interface of the site. The first should be built in such a way that when you change the platform, hosting, language version, you do not need to change the site code. The interface for working with files should be placed in a separate script and ensure full compatibility, just like the design of the site should adequately adapt to any device, browser and provide the rest of the site functionality with the same capabilities.

Read and edit yourself

Can the program change itself, that is, can the script be improved? To this day, this question interests many. But the task sounds much more practical: PHP reading php file. Not always a developer can solve a particular problem by writing specific code. Sometimes it is necessary to change it when a visitor came to the site and formulated a question not provided for at the development stage.

As in all other cases, first of all, the file must be opened. It doesn't matter if the file exists or not. If the file is known to exist (file_exists() returns a positive response), fopen() is used with access 'r', 'r+', 'a', 'a+'. If the file does not yet exist, then with access 'a', 'a+', 'w', 'w+'. The result of opening a file will be its descriptor. The file is closed with the fclose() function.

It is convenient to use PHP reading a file into an array when there is no need to process it at the time of reading.

if (file_exists($fName)) (

$aLines = file($fName)

In this variant, each line of the file enters the array element sequentially. Note that the file() or file_get_contents() functions do not need to open a file and close it.

When the input file is too large, and you need to find very little information, or for other reasons, you can use PHP to read the file line by line. PHP provides the ability to do this with the fgets() and fgetc() functions.

$fvs = fopen($fName, "r")

while ((false !== ($cLine = fgets($fvs, 2000)))) (

$cLines .= "
" . $i . "). " .$cLine

Both options work flawlessly. However, when PHP reads a PHP file for later modification, precautions must be taken. It is far from always possible to foresee options for its use by the visitor at the site development stage. It is better if the scripts are changed within the functions of the site, and the management of this change is not available to the visitor, including the resource administrator.

Saving results

The received and updated information is written to the file by the fputs() function line by line or by the file_put_contents() function in its entirety.

$fName = $_SERVER["DOCUMENT_ROOT"] . "/tmp/scData.php"

$fvs = fopen($fName, "a")

flock($fvs, LOCK_EX)

$cLine = "1 line". chr(10)

fputs($fvs, $cline)

$cLine = "2 lines" . chr(10)

fputs($fvs, $cline)

flock($fvs, LOCK_UN)

In the line-by-line version of the recording, you can manipulate the data during the recording process, in the second case, the string or array being written is placed in the entire file.

$file = "scData.php"

$cContents = file_get_contents($file)

// adding an entry

$cContents .= "new entry\n"

// write file back

file_put_contents($file, $cContents)

Reading and writing PHP files is simple and natural. However, it is important to keep in mind that each file has a name, extension, and path (folder). In order for a PHP script to be able to read and write files, this script must have the appropriate rights. They are automatically exposed on the hosting, but in some cases they need to be expanded.

In some cases, it is desirable to check the results by performing a test read. Writing PHP files requires this at development time, but in some cases, in the interest of site security or trustworthiness, validation of the data entry is essential.

A characteristic feature of PHP, MySQl, JavaScript, and especially browsers: to quietly let some errors drift. “Not recognized, not made…” is not a very good cutting edge practice information technologies, but it teaches developers not to make mistakes and write clean, high-quality code, which is also not bad.

PHP and working with real documents

PHP Reading a PHP file is certainly of practical interest, but this is the realm of programming. The user and site visitor are interested in applied information, which he is used to seeing in the form of tables and documents, in particular, in *.xlsx and *.docx file formats. These are MS Excel and MS Word files.

Lists of goods, prices, characteristics are generally formed in the form of tables, so PHP reading excel file is of significant importance.

PHPExcel and PHPWord libraries have been developed to work with such files. However, the contents of the *.xlsx and *.docx files are presented in the OOXML standard, that is, the real understandable document is represented by a zip archive. Zip archive- this is a set of files, including pictures, objects, formulas, inserts from other programs. Text files are represented here by descriptions in the form of tags. Reading such a file is not enough, you need to parse it in order to get the contents and structure for use and modification.

This means that the read operation turns into an archive opening procedure. These libraries open the document archive on their own and provide the developer with extensive functions for reading, processing and writing such documents.

Excel tables

include_once 'PhpOffice/PhpExcel/IOFactory.php'

function scGetExcelFile($xls)(

$objPHPExcel = PHPExcel_IOFactory::load($xls)

$objPHPExcel->setActiveSheetIndex(0)

//this array contains arrays of strings

$aSheet = $objPHPExcel->getActiveSheet()

$array = array()

//treatment

foreach($aSheet->getRowIterator() as $row)(

$cellIterator = $row->getCellIterator()

foreach($cellIterator as $cell)(

array_push($item, iconv("utf-8", "cp1251", $cell->getCalculatedValue()))

array_push($array, $item)

Reading and processing Excel files is much more difficult than processing Word documents. The best option, if you need to implement a serious project for reading and processing application information, is to first master the PHPWord library. This will give a good experience and a quick entry into the specifics of the issue.

Word Documents

Just two lines:

$oWord = new \PhpOffice\PhpWord\PhpWord()

$oDocx = $this->oWord->loadTemplate($cFileName)

The $cFileName document is now available for processing. Next, the archive is opened, its contents are selected and analyzed, which can be displayed on the site, changed and written back.

$zipClass = new ZipArchive()

$zipClass->open($this->tempFileName)

// read the entire content of the document

for ($i=0; $i<$zipClass->numFiles; $i++) (

$cNameIn = $zipClass->getNameIndex($i)

$cNameInExt = substr($cNameIn, -4)

if (($cNameInExt == ".xml") || ($cNameInExt == "rels")) (

// files with ".xml" and ".xml.rels" extensions are stored in the document table

// each xml line is written with a unique serial number

$cBodyIn = $zipClass->getFromName($cNameIn)

$cBodyInLen = strlen($cBodyIn)

// all other files are written to the document folder as is

$cNameOnly = substr($cNameIn, strrpos($cNameIn, "/") + 1)

$zipClass->getFromName($cNameIn, $cWorkPath); // contents as a file

The possibilities that open up with the help of PHP Excel and PHP Word allow you to manipulate real documents, make their content relevant at any given time. In today's dynamic world, this becomes very important. The center of gravity has long since shifted from local use computer technology into the virtual internet space. Therefore, the creation of tables and documents in local products from Microsoft is less efficient than working with such documents in automatic and semi-automatic mode on a site that is available not only to the creator of the table or document, but also to its consumers.

Text files, another life

To a first approximation, text files are simpler than PHP files or application documents. However, there is something to think about here. The read/write operations of such files are already indicated above, but the meaning of such files is much more important.

Since there is such a given as a client and a server (JavaScript dominates the first, PHP dominates the second), then even the cookie and sessions mechanisms cannot cope with the need to transfer information between scripts, pages, or other processes.

It is possible to reflect the desired changes in the database, but for all their advantages and speed, small temporary or permanent text files can be a much more interesting option for transferring information. If you do not create many small files and control their sizes, then they can be a specific and more flexible version of the database.

PHP reading a text file is fast, it can be immediately parsed into a structure, array or object. The latter is very important, as it allows you to create objects that live outside the time allotted PHP script, which, as you know, can only exist on the server and only at the time of loading the page, generating an AJAX response, or for any other reason that causes the PHP interpreter to start.

If you think about the fact that a text file is the content and structure from the developer, a PHP file is the syntax of the interpreter plus the developer's logic, and "tagged" descriptions html, css, xml are more semantic elements, but regulated by static standards. One can come to the conclusion that it is probably time for the files to acquire new content, and it should itself determine their quality and application logic. Precisely because programming is not yet ready for the next stage of its development, files are now just files that the developer creates and defines their use.

The most interesting and promising thing is when PHP reads a PHP file on its own when the need arises. And simply reading a line from a file in PHP results in the creation of an object, at least in the state in which it was saved. These are not quite familiar ideas, but in fact in modern world everything is changing so fast.

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 lend Perl's motto, "There are more than one way to do things," especially when it comes to handling files. But with the abundance of available tools, the question arises which one is 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 spent.

Traditional fopen methods

The fopen methods are probably the most familiar to C and C++ programmers of the past, as they are, more or less, the very tools that have been at your fingertips for years if you have worked with these programming languages. For any of these methods, you follow the standard procedure of using fopen to open a file, a function to read 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 doing the following steps:

  1. You open the file. $file_handle holds a reference to the file itself.
  2. Check 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. You close the file.

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

fopen function

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

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

This program line 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 read-only. Since writing to a file is out of the scope of this article, I won't list all the possible values ​​for the parameter. However, you need to change "r" to "rb" if you are reading from binary files 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 a value of True (True) or False (False). The loop in continues until the end of "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

Let's 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 brings you to the heart of the file processing process: reading the file itself. The fgets function is the "weapon" you chose 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 process it in some other way. The example in Listing 1 prints the entire file.

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

$string = fgets($file_handle, 81);

Remember "\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 when you need 80 characters. Make it a habit to add an extra character whenever you need to set a string limit for this function.

fread function

The fgets function is just one of many available functions for reading a file. This is one of the most commonly used functions, since line-by-line processing of a file is the most reasonable in most cases. 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 turn to fread . The fread function is used for a slightly different purpose than fgets: it is intended for reading from binary files (that is, files not originally composed of human-readable text). Since the concept of "strings" is not relevant for binary files (logical data structures are usually not split 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 no matter what value you specify, fread will read no more than 8192 bytes (8 KB).

Assuming the file is no larger than 8 KB, the snippet below should read the entire file in 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 it.

fscanf function

Returning to string processing, fscanf is also a 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 documented in many sources such as PHP.net, so I won't repeat that 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, they would be passed as arguments.)

fgetss function

The fgetss function is different from the traditional file functions and gives you a better idea of ​​PHP's capabilities. It works like fgets , but discards any HTML or PHP tags it finds, leaving only the bare text. Take the following HTML file.

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);

Here 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 rest of the data using the standard output pipe with the fpassthru function.

fpassthru($fh);

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

Nonlinear file processing: moving through the file

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

fsee($fh, 0);

The above example jumps back to the beginning of the file. If you don't want to jump 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 want to jump forward 100 bytes from your current position, you can use following code:

fseek($fh, 100, SEEK_CUR);

Similarly, jumping back 100 bytes is done by:

fseek($fh, -100, SEEK_CUR);

If you want to jump back to position 100 bytes 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 that refer to a URL.

Capturing an entire file

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

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

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

echo file_get_contents("myfilename");

This article is primarily about processing local files, however, it's 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 labor intensive." 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 prints 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 single line returned by file_get_contents is probably too much. You may want to split it up first with 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 this work 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, while the file command ends array lines with newlines (same as fgets).

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

Listing 4. Sample .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 may notice that this command has merged sections. This is the default action, but you can easily customize it with 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 puts the data into a multi-dimensional array that is easy to parse.

But this is just the tip of the iceberg when it comes to file handling in PHP. More advanced functions like tidy_parse_file and xml_parse can help you parse HTML and XML documents, respectively. See the section for more detailed information about how these functions work. Both of them are worth considering if you work with files of these types, but instead of considering all possible file types, you can carefully read the contents of this article, where there are some good ones. general rules for 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 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 code will probably be overkill for your task. Handling the values ​​returned by fopen is simpler and more precise.

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

Since fopen returns False on failure, this ensures that the file will only be processed if the file was able to 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 into which all potential problems fall. Alternatively, you can use the program to exit 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 for fclose , there's not much you can do if the file descriptor isn't closed properly, so checking the return value of fclose is usually redundant.

The choice is yours

PHP does not lack effective ways reading and parsing files. Classic functions like fread can serve you well most of the time, or you might be more attracted to the simplicity of readfile if needed to get the job done. The choice really depends on what you're trying to accomplish.

If you're processing large amounts of data, fscanf is likely to be more useful and efficient than, say, using file in combination with subsequent split and sprintf commands. On the other hand, if you're just displaying a large amount of text with minor changes, by contrast, using the file , file_get_contents , or readfile functions might be more appropriate. This solution is likely to be correct using PHP for caching or even creating a temporary proxy server.

PHP provides many tools for working with files. Take a closer look at each of them and find out which tools are best suited for the project you are working on. You are offered a wide choice software tools, make the most of them, and have fun processing your files with PHP.

A computer