Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

Once you have opened a file stream, you can read or write to it using commands like
fgets, and fputs. Listing 7.5 demonstrates this. Notice that a while loop is used to get
each line from the example file. It tests for the end of the file with the feof function.
When you are finished with a file, end of file or not, you call the fclose function. PHP
will clean up the temporary memory it sets aside for tracking an open file.


Keep in mind that PHP scripts execute as a separate user. Frequently this is the "nobody"
user. This user probably won't have permission to create files in your Web directories.
Take care with allowing your scripts to write in any directory able to be served to remote
users. In the simple case where you are saving something like guest book information,
you will be allowing anyone to view the entire file. A more serious case occurs when
those data files are executed by PHP, which allows remote users to write PHP that could
harm your system or steal data. The solution is to place these files outside the Web
document tree.


Listing 7.5 Writing and Reading from a File


<?
/*
* open file for writing
/
$filename = "data.txt";
if(!($myFile = fopen($filename, "w")))
{
print("Error: ");
print("'$filename' could not be created\n");
exit;
}


//write some lines to the file
fputs($myFile, "Save this line for later\n");
fputs($myFile, "Save this line too\n");


//close the file
fclose($myFile);


/*
* open file for reading
/
if(!($myFile = fopen($filename, "r")))
{
print("Error:");
print("'$filename' could not be read\n");
exit;
}


while(!feof($myFile))
{
//read a line from the file
$myLine = fgets($myFile, 255);
print("$myLine
\n");
}

Free download pdf