6.0 Introduction


File access is unarguably an important feature in almost any language, but file access is especially important in Web applications programming. This is so because the Web is stateless ”the program usually ends execution and HTML is returned to the user. (Applets are an exception; they end when the user exits the Web page.) Files (and databases, which are in essence structured files) enable us to remember the user 's last visit or, in some cases, even her last action.

The purpose of this chapter is to show you how to access files and different ways of manipulating files and their contents. You access files in PHP much like you do in C: First, you open the file and assign the returned file pointer to a variable, and then you can read and write (depending on what mode you use) the file contents by accessing the file pointer. Here is an example of reading a file and then printing it out line-by-line :

 <?php $fp = @fopen ("sample.txt", "r") or   die("Cannot Open sample.txt"); while ($line = @fgets ($fp, 1024)) {     print $line; } @fclose($fp) or die("Cannot Close sample.txt"); ?> 

Line 1: Start off the PHP document; I hope this is familiar to you.

Line 3 “4: Open sample.txt with read permissions ( "r" ). The @ suppresses PHP's warning messages. We use or die... to print out a custom error message if the file opening fails.

Line 6: Start off a while loop to move through each line in the file. Now use the fgets() function, which has the following syntax:

 string fgets (int filepointer, int length); 

We then assign the string returned by fgets() to $line so that we can manipulate or print $line .

Line 7: Print the value of $line .

Line 8: Close the file with fclose . This is good practice even though the file is automatically closed when the script stops executing.

Line 9: Close the PHP document.

Perhaps it will help some of you who speak other languages to see the earlier script in a different language. So, for all you Perl programmers, here is the Perl equivalent of the previous script (the while loop can be simplified to print while <FH>; ):

 #!/usr/bin/perl -w use strict; print "Content-type: text/html\n\n"; open FH, "< sample.txt" or die "Cannot open sample.txt: $!"; while (<FH>) {     print; } close FH or die "Cannot close sample.txt: $!"; 

Here is the Python equivalent:

 fp = fopen("sample.txt", "r") print "Content-type: text/html\n\n" while 1:     line = fp.readline()     if not line: break     print line 

The rest of this chapter illuminates some of the tricks of accessing files in PHP.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net