PHP has a lot of file handling functions
File_get_contents reads the contents of the file to return a string. Read failure returns FALSE.
$contents = file_get_contents (' c:/private/filetest01.txt '), if ($contents = = = False) {echo ' Sorry, there was a problem read ing the file. ';} else {//convert contents to uppercase and Displayecho Strtoupper ($contents);}
Why not use the IF (! $content)
The reason I haven ' t used that shortcut this is because the external file might being empty, or you might want it to store a Number. As explained in ' The Truth according to PHP ' in Chapter 3, a 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 was stored on a separate line, with a tab, comma, or other Delimiter between each field (see Http://en.wikipedia.org/wiki/Flat_file_database). When handling this sort of file, it's more convenient to store each line individually in an array of the ready for processing wit H a loop. The PHP file () function builds the array automatically. The following is the file content. Left for name has for password
David, Codeslave
Chris, Bigboss.
The file () function, which is automatically read into each line to create an array:
$tmp [0], ' password ' = RTrim ($tmp [1]); } } else { echo "Can ' t open $textfile"; }? >
Note here:
' 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.
NewLine characters for each line must be manually removed.
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 and is used with any of the other read/write functio Ns. So, the This is what you would 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 ().
To read a file with fopen:
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
Tags.
Echo ("foo isn ' t \ n bar"); \ nthe line is not wrapped at all, and wrapping in HTML is
NL2BR Returns string with '
' or '
' Inserted before all newlines (\ r \ n, \n\r, \ n and \ r).
Output:
Foo isn ' t
Bar
The other-the-to-read the contents of a file with fopen () are to use the fgets () function, which retrieves one line at a Ti Me. This means, 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 do by replacing
$contents = Fread ($file, FileSize ($filename));
With this (the full script was 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 function the same.
Above us fopen () Open mode is W, 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 L Inefwrite ($file, "\r\n$contents");//Close the Filefclose ($file);
Notice that I had enclosed $contents in double quotes and preceded it was carriage return and new line
characters (\ r \ n). This makes sure, the new content is added on a fresh line. When using the-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 useful to has a file created automatically with the same name, it could be exactly the opposite of what You want. To make sure your ' re not overwriting a existing file, you can use the 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 would fail by returning FALSE and generating a 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 is, 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); Rewind back
To move the pointer to the end of a file
This was a little more complex. You need-to-use fseek (), which moves the pointer-a location specified by an offset and a PHP constant. The constant that represents the end of the file was seek_end, so a offset of 0 bytes places the pointer where you want it . You also need-pass fseek () a reference to the open file,
So all three arguments together look like this:
Fseek ($file, 0, seek_end);
Exploring 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 is building a drop-down menu of files and Creati Ng 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!== ($ite m = Readdir ($folder))) {$files [] = $item;} Close Itclosedir ($folder);
The Readdir () function gets one item at a time and uses of internal pointer in the same
The as the functions used with fopen (). To build a list of the directory ' s entire contents,
You need to use a while loops and store each result in an array. The condition for The loop
is contained on the following line:
while (false!== ($item = Readdir ($folder))) {
The Readdir () function returns False when it can find no more items, so to prevent the
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. The file name is returned as a sort in the file system.
Please note that the following example examines the style of the Readdir () return value. We explicitly test whether the return value is all equal (the value and type are the same-more information see comparison operators) False, otherwise the name of any catalog item evaluates to False to cause the loop to stop (for example, a directory named "0").
Note that Readdir () will be returned. And.. Entry. If you don't want them, just filter them out.
List all files in the current directory and remove them. And..
Personal notes:
Opendir only support local directory, do not support http:.//directory, if error: failed to open Dir:not implemented this is the problem,
It's better to use relative catalogs.
Building a drop-down menu of files
$filename \ n ';}}} ? >
After the folder have been opened, each item is
Passed to a PHP function called PathInfo (), which returns an associative array with the
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)
/www/htdocs/inclib.inc.phpphplib.inc
For a directory, extension is not.
Because the extension element is not returned for a directory, you need
Array_key_exists () before attempting to check its value. The second half of the conditional
Statement in line uses In_array () to see if the value of extension matches one
The of the file types that "re looking for. It there ' s a match, the filename is added to the
$found Array. It's then just a case of building theElements with a foreach loop,
But to add a user-friendly touch, the $found array was 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 what to create a unique filename by adding a timestamp
The 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, a PHP script has the no-to-keep track of a series of
Numbers between requests to the server. However, by inspecting the contents of a directory,
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)
<title>Create series of consecutively numbered files</title>
$result"; }?>
Opening Remote Data sources
PHP can open publicly available files on other servers just as easily as on the same server.
This is particularly useful for accessing XML files or news feeds. All so you need
Pass the URL as a argument to the function. Unfortunately, as noted earlier, many hosting
Companies disable the Allow_url_fopen setting in PHP. One-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:
omitted here temporarily.