You'll often need to establish a connection to a file resource before you can do anything with its contents. Likewise, once you've finished working with that resource, you should close the connection. Two standard functions are available for such tasks, both of which are introduced in this section.
resource fopen (string resource, string mode [, int use_include_path
The fopen() function binds a resource to a stream, or handler. Once bound, the script can interact with this resource via the handle. Most commonly, it's used to open files for reading and manipulation. However, fopen() is also capable of opening resources via a number of protocols, including HTTP, HTTPS, and FTP, a concept discussed in Chapter 16.
The mode, assigned at the time a resource is opened, determines the level of access available to that resource. The various modes are defined in Table 10-1.
If the resource is found on the local file system, PHP expects the resource to be available by either the local or relative path prefacing it. Alternatively, you can assign fopen()'s use_include_path parameter the value of 1, which will cause PHP to consider the paths specified in the include_path configuration directive.
The final parameter, zcontext, is used for setting configuration parameters specific to the file or stream, and for sharing file- or stream-specific information across multiple fopen() requests. This topic is discussed in further detail in Chapter 16.
Let's consider a few examples. The first opens a read-only stream to a text file residing on the local server:
$fh = fopen("/usr/local/apache/data/users.txt","rt");
The next example demonstrates opening a write stream to a Microsoft Word document. Because Word documents are binary, you should specify the binary b mode variation.
$fh = fopen("/usr/local/apache/data/docs/summary.doc","wb");
The next example refers to the same Word document, except this time PHP will search for the file in the paths specified by the include_path directive:
$fh = fopen("summary.doc","wb", 1);
The final example opens a read-only stream to a remote index.html file:
$fh = fopen("http://www.example.com/", "rt");
You'll see this function in numerous examples throughout this and the next chapter.
boolean fclose (resource filehandle)
Good programming practice dictates that you should destroy pointers to any resources once you're finished with them. The fclose() function handles this for you, closing the previously opened file pointer specified by filehandle, returning TRUE on success and FALSE otherwise. The filehandle must be an existing file pointer opened using fopen() or fsockopen().
Please check back for the next part of the series.
blog comments powered by Disqus