The ftell Function—Finding the Current Position in a File If you have read some data from a file and want to keep track of where you were in the file when you stopped reading, the ftell
Trang 1The ftell() Function—Finding the Current Position in a File
If you have read some data from a file and want to keep track of where you were in the file when you stopped reading, the ftell() function will return the current byte position, the number of bytes from the beginning of the file, and where the next read operation will start This can be used in conjunction with the seek() function to return to the correct position in the file (If you are using text mode, the carriage return and linefeed translation will be part of the byte count.)
Format
int ftell ( resource handle )
Example:
$filehandle("myfile", "r"); $contents=fgets($filehandle, 1024); echo ftell(
$filehandle); // Current read postion in bytes, // starting at byte 1024
Trang 311.2.6 Opening a URL for Reading
You can open files with FTP or HTTP with the fopen() function (Note: If opening the URL fails, check if the allow_url_fopen directive in the php.ini file is disabled.)
Format
resource fopen ( string filename, string mode [, bool
use_include_path [, resource zcontext]] )
Trang 4Figure 11.11 Viewing the contents of a Web page opened as a URL
11.2.7 Reading from Files Without a Filehandle
PHP provides functions that allow you to read the contents of a file without first opening a filehandle
The file_get_contents() Function—Reading the Whole File into a String
An easy way to read the contents of an entire file is with the file_get_contents() function You do not even
need to get a filehandle, just pass the name of the file to the function and it will get the contents of the whole file and
store it in a string You can also start reading from a specified offset in the file and specify how many bytes you want to
read The file_get_contents() function will return FALSE, if it fails The PHP manual suggests this as the most
efficient way to read a file into a string
The file() Function—Reading the Whole File into an Array
Without using a filehandle, you can read an entire file into an array with PHP’s file() function The filename can be
a full path, relative path, or even a URL (if each element of the array corresponds to a line in the file, with the newline
still attached The function returns FALSE if it fails If you do not want the end-of-line character at the end of each of
the array elements, use the rtrim() function, described in Chapter 6, “Strings.”[5] This function is identical to
file_get_contents(), except that it returns the file in an array
[5] If PHP does not recognize the line endings (Macintosh), see the php.ini file to enable the
auto_detect_line_endings runtime configuration option
Format
array file ( string filename [, int use_include_path [, resource
context]] )
Trang 5action="<?php echo $_SERVER['PHP_SELF'];?>">
<table cellspacing="0" cellpadding="2">
<tr>
<b> Select a first name from the file.</b>
<td><input type="text" size=30
Trang 7Figure 11.12 Using the file() function, creating line numbers
Using explode() and implode()
After you have read in a line from a file or you get input from a file, you might want to break the lines into individual fields or create a string from an array of input items This is where the array functions explode() and implode() can be useful, array functions discussed in Chapter 8, “Arrays.”
Example 11.12 demonstrates how to use these functions This example uses the text file called datebook.[6] Below are two lines from this file Notice that the fields are separated by colons
[6] The datebook file can be found on the CD in the back of this book
Steve Blenheim:238-923-7366:95 Latham Lane, Easton, PA 83755:11/12/56:20300 Betty Boop:245-836-8357:635 Cutesy Lane, Hollywood, CA 91464:6/23/23:14500
Trang 8action="<?php echo $_SERVER['PHP_SELF'];?>">
<table cellspacing="0" cellpadding="2">
<tr>
<b> Select a first name from the file.</b>
<td><input type="text" size=30
Trang 9file()
$first_namePOST
trim()foreach
Trang 11Figure 11.14 After the lines in the file have been parsed Output from Example 11.12
The readfile() Function—Reading and Writing a File
The readfile() function reads from a file and writes it to the output buffer It returns the number of bytes read from the file If an error occurs, FALSE is returned and an error message is printed
Trang 1311.2.8 Opening a File for Writing and Appending
When you open a file for writing, the file is created if it does not exist, and truncated if it does If you open a file for appending, the file will not be overwritten if it exists and the data will be appended to the bottom of the file If it does not exist, opening for appending creates the file
To open a file for writing, the fopen() function returns a filehandle to either a text or binary file Although UNIX and MacOS do not distinguish between text and binary files, Windows does If a file is to be shared by multiple operating systems, it is safer to open it in binary mode in conjunction with one of the other modes (As of PHP 4.3.2, the default mode is set to binary for all platforms that distinguish between binary and text mode.)
UNIX and MacOS X represent the end-of-line character with \n, whereas Windows uses \r\n If you use Windows, the "t" mode can be used with plain-text files to translate the \n to \r\n Otherwise, the "b" mode should be used, which does not interpret data but treats it as just a series of bytes If the file contents look weird when it is opened or you have a lot broken images, use the "b" mode
$handle = fopen("/home/marko/file.txt", "wb"); $handle =
fopen("http://www.ellieq.com/", "w"); $handle =
fopen("ftp://user:password@ellieq.com/myfile.txt", "a");
The fwrite() and fputs() Functions
The fwrite() function writes a string text to a file and returns the number of bytes written An alias for the
fwrite() function is fputs() It takes two arguments: the filehandle returned by fopen() and an optional length argument, how many bytes to write to the file If it fails, fwrite() returns FALSE
The file_put_contents() Function
The file_put_contents() also writes a string to a file and returns the number of bytes written, but does not require a filehandle Otherwise it is the same as fwrite() and fputs()
(Output: Contents of info.txt)
Joe Shmoe Jr 100 Main St jshmoe@whatever.mil Major
Trang 14Explanation
file
mydirinfo.txt
$filehandlestrlen()
Trang 15Figure 11.16 After writing and appending Output from Example 11.15
Locking Files with flock()
What if two or more customers are trying to write to a Web site at the same time? To prevent this, you can lock the file
so that a user has exclusive access to it and then unlock it when he or she has finished using it PHP supports a portable way of locking complete files with the flock() function This is called advisory locking because all accessing programs have to use the same locking mechanism or it will not work See Table 11.6 for a list of flock() operations
Table 11.6 flock() Operations
The flock() function uses a filehandle returned from the fopen() function The lock can be released by
fclose(), which is also called automatically when the script finished The function returns TRUE on success or FALSE on failure Whether or not this function works properly is entirely dependent on your operating system; for example, it is not supported on older systems like Windows 98 or for networked file systems (NFS), and so on
Trang 1711.2.9 File Checks
Before performing operations on files or directories, it is a good practice to verify whether or not the file even exists, if
it is readable, writable, executable, and so on PHP provides a set of functions for testing the status of a file See Table 11.7
Table 11.7 File Testing Functions
The file_exists() Function
The file_exists() function checks to see whether a file or directory exists It returns TRUE if it does, and FALSE
echo "<img src='logo_i.gif'><br />";
Trang 18The is_file() Function
The is_file() function checks to see if a file exists and is a regular file; that is, not a directory It takes the name of the file as its argument and returns TRUE if the file is a regular file, and FALSE if it is not.[7]
[7] Processing is faster if you use a relative path name rather than an absolute path
Trang 19Figure 11.17 The file exist, but it is not a plain file Output from Example 11.18
The is_readable() Function
The is_readable() function checks to see if you can read from a file It takes the filename as its argument and returns TRUE if the filename exists and is readable If the PHP script is being executed by the server, the server’s permissions (usually limited) determine whether or not the PHP program can read from the file, and if it is being executed at the shell prompt, the permissions of the user running the script are the deciding factor Normally, the file should be readable by others
Trang 20The is_writable() Function
When opening a file for writing, you might run into a problem with permissions if you are trying to put the file in a directory not accessible to the Web Because the PHP script is executed on behalf of the server, it shares the same permissions Normally, the server does not have world-write permissions turned on to prevent hackers from breaking into your site and causing havoc
The is_writable() (or is_writeable) function returns true if a file exists and is writable, and false if it is not
is_writeable()
Trang 21Figure 11.18 This file is not writable Output from Example 11.20
fwrite($fp, $outputstring, strlen($outputstring));
echo "Output was sent to $filename<br />";
@
Trang 224 fopen() $fp
Figure 11.19 Suppressing PHP errors and printing your own Output from Example 11.21
11.2.10 Creating, Copying, Renaming, and Deleting Files
Table 11.8 lists functions for creating, copying, renaming, and removing files This section examines these functions
Table 11.8 Functions to Manipulate Files
The copy() Function—Making a Copy of a File
To make a copy of a file, the copy() function is used The copy() function will return true if the file was correctly copied, or false if there was an error To copy a file, you will need write permission on the directory where the new
copy will be stored
3 if(! copy($oldfilename, $newfilename)){
echo "Copy failed\n<br />";
exit();
Trang 23The rename() Function—Renaming and/or Moving a File
The rename() function is used to give a file or directory another name If the destination file is in another directory, then you are essentially moving the file It returns true on success, and false if it fails
Format
bool rename(string old_file,string new_file)
Example:
rename("/tmp/tmpfile", "/home/ellie/exemples/data.txt");
The unlink() Function—Removing a File
The unlink() function is used to remove a file It returns true if it can remove the file and false if not
in the following examples
Table 11.9 PHP Directory Functions
Trang 24Table 11.9 PHP Directory Functions
11.3.1 Opening and Reading from a Directory
When you open a directory with the opendir() function, you create a directory handle to allow access to the directory as it is stored on the disk by the operating system regardless of its internal structure Once it is opened, you can access the directory with the PHP functions listed in Table 11.9
The opendir() Function
The opendir() function is used to open a directory, similar to the fopen() function for opening files Once a handle to the directory is returned, the other directory functions, such as readdir(), rewindir(), and
closedir(), can be applied to the directory filehandle If the directory cannot be opened, false will be returned
The readdir() Function
A directory can be read by anyone who has read permission on the directory When we speak of reading a directory, we are talking about looking at its contents with the readdir() function readdir() reads an entry from a directory handle, given as its argument, and returns the name of a file from the directory Each file appears in the order in which
it is stored by the file system on the disk You can use this function in a loop to list the contents of the entire directory, one file at at time The readdir() function returns either a filename, or false if it fails If it succeeds, it moves its internal pointer to the next file in the directory, until it reaches the end of the list
Trang 25<h3>Listing the Contents of a Directory</h3>
Trang 2611.3.2 Getting Path Information
The dirname() function returns the name of the directory from a path name and the basename() function returns the name of a file without the directory component A dot indicates the current working directory
11.3.3 Changing and Getting the Current Directory
The chdir() function changes to a specified directory You can use either relative or absolute path names The function returns true on success, and false on failure
The getcwd() function returns the path to the current working directory if successful, and false if not
1 echo getcwd(),"\n<br />"; // Get the current directory
2 chdir(" "); // Change directory; go up one level
echo getcwd(),"\n<br />";
?>
</body>
</html>
Trang 27Explanation
getcwd()chdir()
Figure 11.21 Changing directory and printing the current directory
11.4 Managing Content with Include Files
As your site adds more pages, you will find it easier to maintain if you manage the content with template files, external files that separate the content, HTML client-side instructions, from the application, the PHP server-side programming instructions Creating a structure for your site will not only make it more manageable for designers and programmers, but easier to navigate and debug This section focuses on how to include simple files to help manage content (There are many templating solutions available for PHP today easily found on the Web See http://smarty.php.net to find about Smarty, a template engine designed for PHP.)
To include files in your PHP program, the PHP include() and require() functions are used When a file is included, it is similar to a copy and paste operation The contents of the included or required file are placed within the file in the same way Often, a convention is to name the included file with an inc extension and store it in a directory outside the document tree
The require() and include() statements are identical in every way except how they handle failure The
include() produces only a warning if the file cannot be found, whereas require() results in a fatal error causing the program to die (Be sure that the file you include or require can be located by updating the include_path directive in the php.ini configuration file.)
Examples:
// Replaces instances of require with the contents of file; // fatal error if file is missing require("copyright.inc"); // Replaces only first instance of require with contents of file require_once("header.inc"); // Same as replace() but produces a warning if file is missing include("disclaimer.inc"); // Happens only once during program execution include_once("footer.inc");
11.4.1 A Real-World Example
In the following example, we create a file called header.php that contains the HTML design for the top of the Web page; next, the page that contains the body of the document, that is, the PHP instructions to open a database to retrieve and display information; and finally the footer page, called footer.php with copyright information to appear at the