Php how to pronounce. Working with files in php: opening, writing, reading. Traditional fopen methods

Last update: 1.11.2015

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

Reading and writing files

Opening and closing files

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

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

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

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

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

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

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

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

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

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

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

Reading a file

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

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

Reading the entire file

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

Block reading

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

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

Write a file

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

Another fputs() function works similarly:

Working with the file pointer

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

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

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

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

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

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

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

Example of using the function:

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

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 language motto, "There is more than one way to do something", especially when we're talking about about 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 perhaps 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 do 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 argument to fgets to limit maximum length lines of captured data. 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 it finds. HTML tags or PHP, 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);

Likewise, moving 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 you make it easier? The process is almost ridiculously easy 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 parts 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 merged 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 the 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 to get more detailed information about the operation of these functions. Both of them are worth considering if you work with these types of files, but instead of looking at all possible file types, you may want to take a closer look at the contents of this article, where there are several good general rules for working with the functions I have described so far.

Good programming style

Never assume that everything in your program will work as intended. For example: what if the file you are looking for has been moved? What if 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 effective ways reading and analyzing 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 likely 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 if 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 choice software, use them most effectively and have fun processing your files with PHP.

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

General remarks

The main work with files, whatever they are, consists of opening, reading/writing and closing. 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 is the same as before, in the distant past.

An important point in PHP is the abundance of functions for working with files and options for using them. In practice, it is enough to use simple but working options. A file is, first of all, program memory. You can store information in it. The purpose of any program, the purpose of any website is to present, process and ensure the safety of information.

Essential circumstance

Previously, the requirement for compatibility, at least from bottom to top, was unshakable. That is, a program once written in one version of a programming language is ideally compiled/interpreted in the next version. In modern programming this is not the case. The requirement for compatibility of syntactic structures of a language has become a thing of history, and the struggle between styles and programming tools and versions of certain tools has become the norm of their life.

Working with files, as well as with databases, is as important as the site interface. The first should be built in such a way that when changing the platform, hosting, or language version, there is no need to change the site code. The interface for working with files must be included in a separate script and ensure full compatibility, just as the site design must adequately adapt to any device, browser and provide the rest of the site’s functionality with the same capabilities.

Read and change yourself

Can a program change itself, that is, can a script improve? To this day, this question interests many. But the task sounds much more practical: PHP reading a PHP file. A developer cannot always solve a particular problem by writing specific code. Sometimes it is necessary to change it when a visitor comes to the site and formulates a question that was not foreseen at the development stage.

As in all other cases, first of all you need to open the file. It doesn't matter whether this file exists or not. If it is known that the file exists (the file_exists() function gives a positive answer), the fopen() function is used with access 'r', 'r+', 'a', 'a+'. If the file does not exist yet, 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 to read 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 option, each line of the file goes into the array element sequentially. It should be noted that the file() or file_get_contents() functions do not need to open the file and close it.

When the input file is too large and you need to find just a little bit of 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 performing PHP reading of a PHP file for later modification, precautions should be taken. It is not always possible to foresee how a visitor will use it at the site development stage. It is better if the scripts are changed within the site’s functions, and control 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 as a whole.

$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 line" . chr(10)

fputs($fvs, $cLine)

flock($fvs, LOCK_UN)

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

$file = " scData.php "

$cContents = file_get_contents($file)

// adding an entry

$cContents .= "new entry\n"

// write the file back

file_put_contents($file, $cContents)

Reading and writing PHP files is easy and natural. However, it is important to keep in mind: each file has a name, extension and path (folder). In order for a PHP script to be able to read and write files, the 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 may be desirable to verify the results by performing a test read. Writing PHP files requires this during development, but in some cases, in the interests of site security or reliability, checking data recording is essential.

A characteristic feature of PHP, MySQl, JavaScript, and especially browsers: quietly allowing some errors to happen. “Not recognized, not done...” - not a very good frontline practice information technologies, but this 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 information of an applied nature, which he is used to seeing in the form of tables and documents, in particular, in *.xlsx and *.docx file formats. These are files in MS Excel and MS Word format.

Lists of goods, prices, characteristics are usually formed in the form of tables, so PHP reading the Excel file is essential.

The 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 presented in a zip archive. A Zip archive is a set of files, including pictures, objects, formulas, and inserts from other programs. Text files here are represented by descriptions in the form of tags. Reading such a file is not enough; you need to parse it 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 independently 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 to process Word documents. The best option, if you need to implement a serious project for reading and processing applied information, is to first master the PHPWord library. This will give you good experience and a quick understanding of 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 website, changed and written back.

$zipClass = new ZipArchive()

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

// read the entire contents 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 extensions ".xml" and ".xml.rels" are saved in the document table

// each xml line is written with a unique number in order

$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); // content as a file

The opportunities that open up when PHP help Excel and PHP Word allow you to manipulate real documents and make their content relevant at any given time. In today's dynamic world, this becomes very important. The center of gravity has long since passed from local use computer equipment into the virtual Internet space. Therefore, creating tables and documents in local Microsoft products is less efficient than working with such documents in automatic and semi-automatic mode on a website, which is accessible 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 (the first is dominated by JavaScript, the second by PHP), then even the cookie and sessions mechanisms cannot cope with the need to transfer information between scripts, pages, or certain 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 transmitting information. If you don't create a lot of small files and control their size, they can be a specific and more flexible version of a database.

PHP reading a text file is fast, it can immediately be 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 the page is loaded, an AJAX response is generated, or for another reason that causes the PHP interpreter to launch.

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 may come to the conclusion that it is probably time for the files to acquire new content, and this itself should determine their quality and logic of use. It is precisely because programming is not yet ready for the next stage of its development that files today remain simply files that the developer creates and determines their use.

The most interesting and promising thing is when PHP reads a PHP file independently when the need arises. And a simple PHP reading a line from a file results in the creation of an object, at least in the state in which it was saved. These are not entirely familiar ideas, but in the modern world everything changes so quickly.

16.5K

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+ – the 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 in operating system Windows.

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 close.

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


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

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 file modification time. If there is no element with the searched name, it will be created. Its syntax.




Top