Php file management

Source: Internet
Author: User
Tags fread rewind alphanumeric characters
Php manages files. php has many file processing functions.

File_get_contents returns a string for reading the content in the file. If the Read fails, false is returned.

$contents = file_get_contents('C:/private/filetest01.txt');if ($contents === false) {echo 'Sorry, there was a problem reading the file.';}else {// convert contents to uppercase and displayecho strtoupper($contents);}

Why not use if (! $ Content)

The reason I haven'tused that specified cut here is because the external file might be empty, or you might want it to store a number. as explained in "The truth according to PHP" in Chapter 3, an empty string and 0 also equate to false. so, in this case, I 've used the identical operator (three equal signs), which ensures that both
The value and the data type are the same.

Text files can be used as a flat-file database? Where each record is stored on a separate line, with a tab, comma, or other delimiter between each field (see ). when handling this sort of file, it's more convenient to store each line inpidually in an array ready for processing with a loop. the PHP file () function builds the array automatically. the following is the file content. There is password for name on the left.

David, codeslave
Chris, bigboss

The file () function automatically reads each line to create an array:

  $tmp[0], 'password' => rtrim($tmp[1]));    }  }else {  echo "Can't open $textfile";  }?>


'password' => rtrim($tmp[1]));

If a line ends in a new line character, the file () function doesn' t remove it, so you need to do it yourself.

Line breaks of each line must be removed manually.

Opening and closing files for read/write operations

Fopen (): Opens a file
Fgets (): Reads the contents of a file, normally one line at a time
Fread (): Reads a specified amount of a file
Fwrite (): Writes to a file
Feof (): Determines whether the end of the file has been reached
Rewind (): Moves an internal pointer back to the top of the file
Fclose (): Closes a file

The fopen () function returns a reference to the open file, which can then be used with any of the other read/write functions. so, this is how you wowould open a text file for reading:
$ File = fopen ('C:/private/filetest03.txt ', 'r ');
Thereafter, you pass $ file as the argument to other functions, such as fgets (), feof (), and fclose ().

Use fopen to read files:


String fread (resource $ handle, int $ length) reads up to length bytes from the file pointer referenced by handle.

The nl2br () function in the final line converts new line characters to XHTML

Echo ("foo ISN'T \ n bar"); \ n does not have a line feed at all, and the line feed in html is

Nl2br Returns string'
'Inserted before all newlines (\ r \ n, \ n \ r, \ n and \ r ).



foo isn't

The other way to read the contents of a file with fopen () is to use the fgets () function, which retrieves one line at a time. this means that you need to use a while loop inUSING php to manage files combination with feof () to read right through to the end of the file. this is done by replacing this line

$contents = fread($file, filesize($filename));

with this (the full script is in fopen_readloop.php)// create variable to store the contents$contents = '';// loop through each line until end of filewhile (!feof($file)) {// retrieve next line, and add to $contents$contents .= fgets($file);}

Write file:


form id="writeFile" name="writeFile" method="post" action="">    

Write this to file:

Fputs () and fwrite () are synonymous and have the same functions.

The above fopen () open mode is w, and the previous text will be overwritten.

Appending content with fopen ()

// open the file in append mode$file = fopen('C:/private/filetest04.txt', 'a');// write the contents after inserting new linefwrite($file, "\r\n$contents");// close the filefclose($file);

Notice that I have enclosed $ contents in double quotes and preceded it by carriage return and new line
Characters (\ r \ n). This makes sure that the new content is added on a fresh line. When using this on Mac
OS X or a Linux server, omit the carriage return, and use this instead:
Fwrite ($ file, "\ n $ contents ");

Writing a new file with fopen ()

Although it can be useful to have a file created automatically with the same name, it may be exactly the opposite of what you want. to make sure you're not overwriting an existing file, you can use fopen () with x mode.

'X' Create and open for writing only; place the file pointer at the beginning of the file. if the file already exists, the fopen () call will fail by returning FALSE and generating an error of level E_WARNING.

That is, the same file can only be written once.

Moving the internal pointer

Since reading and writing operations always start wherever the internal pointer happens to be, you normally want it to be at the beginning of the file for reading, and at the end of the file for writing.

To move the pointer to the beginning of a file Pass the reference to the open file to rewind () like this:
Rewind ($ file); reverse

To move the pointer to the end of a file

This is a little more complex. you need to use fseek (), which moves the pointer to a location specified by an offset and a PHP constant. the constant that represents the end of the file is SEEK_END, so an offset of 0 bytes places the pointer where you want it. you also need to pass fseek () a reference to the open file,

So all three arguments together look like this:

Fseek ($ file, 0, SEEK_END );

ING the file system

PHP's file system functions can also open directories (folders) and inspect their contents. from a web designer's viewpoint, the most practical applications of this are building a drop-down menu of files and creating a unique name for a new file.

Array scandir (string $ directory [, int $ sorting_order = SCANDIR_SORT_ASCENDING [, resource $ context])

List files and directories inside the specified path.

Opening a directory to inspect its contents

// open the directory$folder = opendir('../images');// initialize an array to store the contents$files = array();// loop through the directorywhile (false !== ($item = readdir($folder))) {$files[] = $item;}// close itclosedir($folder);

The readdir () function gets one item at a time and uses an internal pointer in the same
Way as the functions used with fopen (). To build a list of the directory's entire contents,
You need to use a while loop and store each result in an array. The condition for the loop
Is contained in the following line:
While (false! ==( $ Item = readdir ($ folder ))){
The readdir () function returns false when it can find no more items, so to prevent
Loop from coming to a premature end if it encounters an item named 0, for example, you
Need to use false with the nonidentical operator (! = ).

Each time the while loop runs, $ item stores the name of the next file or folder, which is
Then added to the $ files array. Using this trio of functions isn't difficult, but the one-line
Scandir () is much simpler.

String readdir (resource dir_handle)
Returns the file name of the next file in the directory. File names are returned in the order in the file system.

Check the style of readdir () returned values in the following example. We explicitly test whether the returned values are all equal to (both values and types are the same-for more information, see Comparison operators) FALSE, otherwise, if the name of any directory item is evaluated as FALSE, the loop will be stopped (for example, a directory named "0 ").

Note that readdir () will return the... and .. entries. If you don't want them, just filter them out.

List all files in the current directory and remove ..


Personal notes:

Opendir only supports local directories and does not support http:. // directories. if the error is: failed to open dir: not implemented,

It is better to use a directory.

Building a drop-down menu of files


 $filename\n";        }      }    }  }?>

After the folder has been opened, each item is
Passed to a PHP function called pathinfo (), which returns an associative array with
Following elements:

Dirname: The name of the directory (folder)
Basename: The filename, including extension (or just the name if it's a directory)
Extension: The filename extension (not returned for a directory)



Extension does not exist for a directory.

Because the extension element is not returned for a directory, you need to use
Array_key_exists () before attempting to check its value. The second half of the conditional
Statement in line 12 uses in_array () to see if the value of extension matches one
Of the file types that you're looking for. It there's a match, the filename is added to
$ Found array. It's then just a case of buildingElements with a foreach loop,
But to add a user-friendly touch, the $ found array is first passed to the natcasesort ()
Function, which sorts the filenames in a case-insensitive order.

Automatically creating the next file in a series

In the last chapter I showed you how to create a unique filename by adding a timestamp
Or using the date () function to generate the date and time in human-readable format. It
Works, but is hardly ideal. A numbered series, such as file01.txt, file02.txt, and so on,
Is usually better. The problem is that a PHP script has no way to keep track of a series
Numbers between requests to the server. However, by inspecting the contents of a directory,
You can use pattern matching to find the highest existing number, and assign the next
One in the series.

I 've turned this into a function called getNextFilename ()
The function takes the following three arguments:
The pathname of the directory where you want the new file to be created
The prefix of the filename, which must consist of alphanumeric characters only
The filename extension (without a leading period)

 Create series of consecutively numbered files

"; }?>


Opening remote data sources

PHP can open publicly available files on other servers just as easily as on the same server.
This is special useful for accessing XML files or news feeds. All that you need to do is

Pass the URL as an argument to the function. Unfortunately, as noted earlier, without hosting
Companies disable the allow_url_fopen setting in PHP. One way to get around this is
To use a socket connection instead.
To create a socket connection, use the fsockopen () function, which takes the following
Five arguments:

This is omitted temporarily.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.