Php reading file from the end. PHP: Read a PHP file. Working with files in PHP: reading, writing and recommendations. Creating and deleting files

PHP

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

Files: operating modes

PHP

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

Opening and closing files in PHP

PHP

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

Reading files in PHP

PHP

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

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

Cursor manipulation in PHP files

PHP

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

Direct work with files (data) in PHP

PHP

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

Managing files in php

PHP

copy(string source, string destination); // Copying the file rename(str oldname, str newname); // Rename the file unlink(string filename); // Deleting a file

Uploading files to PHP server

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

HTML

Working with files on the server

PHP

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

Returns a string of length - 1 byte read from the file descriptor pointed to by handle . The read ends when the number of bytes read reaches length - 1, when it reaches the end of the line (which is included in the return value), or when it reaches the end of the file (whichever comes first). If length is not specified, it defaults to 1 kilobyte or 1024 bytes.

If an error occurs, the function returns FALSE .

The most common mistakes:

Programmers accustomed to the semantics of "C" functions fgets(), must take into account the difference in how the end-of-file (EOF) flag is returned.

The file pointer must be valid and point to a file successfully opened by the functions fopen() or fsockopen() .

Below is a simple example:


Example 1. Reading a file line by line

$handle = fopen("/tmp/inputfile.txt" , "r" );
while (! feof ($handle )) (
$buffer = fgets($handle, 4096);
echo $buffer ;
}
fclose($handle);
?>

Comment: The length parameter became optional starting with PHP version 4.2.0. If this parameter is omitted, the length of the string is assumed to be 1024. As of PHP 4.3, omitting the length parameter will cause the stream to be read to the end of the string. If most of the lines in the file are longer than 8 kilobytes, the most efficient decision regarding the resources used by the script is to specify a maximum line length.

Comment: This function can correctly process binary data starting from PHP 4.3. Earlier versions did not have this functionality.

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

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

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 met - “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.

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

file_get_contents — Reads the contents of a file into a string

Description

String file_get_contents (string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]])

This function is similar to the function file() with the only difference being that file_get_contents() returns the contents of the file in a string, starting at the specified offset and up to maxlen bytes. In case of failure, file_get_contents() will return FALSE.

Using the function file_get_contents() It is most preferable if you need to get the entire contents of a file, since the function uses a file-to-memory mapping technique to improve performance, if supported by your operating system.

Comment:

If you are opening a URI containing special characters such as space, you need to encode the URI using urlencode().

List of parameters

The name of the file being read.

Use_include_path

Comment:

Since PHP 5 you can use the constant FILE_USE_INCLUDE_PATH to search for a file in include path.

context

A valid context resource created using the function stream_context_create(). If there is no need to use a special context, you can skip this parameter by passing the value NULL.

The offset at which reading of the original stream will begin.

Offset search is not supported when working with remote files. Trying to find an offset on non-local files may work for small offsets, but the result is unpredictable since it is running on a buffered stream.

Maximum size of data read. By default, reading is performed until the end of the file is reached. Note that this setting also applies to streams with filters.

Return values

The function returns the read data or FALSE in case of an error.

Attention

This function can return as boolean FALSE, and a non-boolean value that is cast to FALSE. For more information, see the Boolean type section. Use the === operator to check the value returned by this function.

Errors

A level error will be generated E_WARNING, if the filename parameter cannot be found, the maxlength parameter is less than zero, or the search at offset offset in the stream fails.

Examples

Example #1 Get and display the source code of a website's home page

$homepage = file_get_contents("http://www.example.com/");
echo $homepage ;
?>

Example #2 Finding files in include_path

// <= PHP 5
$file = file_get_contents("./people.txt" , true );
// > PHP 5
$file = file_get_contents("./people.txt" , FILE_USE_INCLUDE_PATH );
?>

Example #3 Reading a section of a file

// Read 14 characters, starting from character 21
$section = file_get_contents("./people.txt" , NULL , NULL , 20 , 14 );
var_dump($section);
?>

The result of running this example will be something like this:

string(14) "lle Bjori Ro"

Example #4 Using Streaming Contexts

// Create a thread
$opts = array(
"http" =>array(
"method" => "GET" ,
"header" => "Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
);

$context = stream_context_create ($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents ("http://www.example.com/" , false , $context );
?>

Close_notify. PHP will report this as "SSL: Fatal Protocol Error" the moment you reach the end of the data. To get around this, you should set error_reporting to a level that excludes E_WARNING. PHP versions 4.3.7 and older can detect that there is a problematic IIS on the server side when opening a stream using a wrapper https:// and does not display a warning. If you are using fsockopen() for creating ssl:// socket, it is your responsibility to detect and suppress this warning.