|
Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index
PHP Script Tips - Reading and Writing Files
By: FYICenter.com
Part:
1
2
3
4
(Continued from previous part...)
What's Wrong with "while ($c=fgetc($f)) {}"?
If you are using "while ($c=fgetc($f)) {}" to loop through each character
in a file, the loop may end in the middle of the file when there is a "0" character,
because PHP treats "0" as Boolean false. To properly loop to the end of the file,
you should use "while ( ($c=fgetc($f)) !== false ) {}".
Here is a PHP script example on incorrect testing of fgetc():
<?php
$file = fopen("/temp/cgi.log", "w");
fwrite($file,"Remote host: 64.233.179.104.\r\n");
fwrite($file,"Query string: cate=102&order=down&lang=en.\r\n");
fclose($file);
$file = fopen("/temp/cgi.log", "r");
while ( ($char=fgetc($file)) ) {
print($char);
}
fclose($file);
?>
This script will print:
Remote host: 64.233.179.1
As you can see the loop indeed stopped at character "0".
How To Read a File in Binary Mode?
If you have a file that stores binary data, like an executable program or picture file,
you need to read the file in binary mode to ensure that none of the data gets modified
during the reading process. You need to:
- Open the file with fopen($fileName, "rb").
- Read data with fread($fileHandle,$length).
Here is a PHP script example on reading binary file:
<?php
$in = fopen("/windows/system32/ping.exe", "rb");
$out = fopen("/temp/myPing.exe", "w");
$count = 0;
while (!feof($in)) {
$count++;
$buffer = fread($in,64);
fwrite($out,$buffer);
}
fclose($out);
fclose($in);
print("About ".($count*64)." bytes read.\n");
?>
This script will print:
About 16448 bytes read.
This script actually copied an executable program file ping.exe in binary mode to new file.
The new file should still be executable. Try it: \temp\myping dev.fyicenter.com.
How To Write a String to a File with a File Handle?
If you have a file handle linked to a file opened for writing, and you want
to write a string to the file, you can use the fwrite() function. It will write the string
to the file where the file pointer is located, and moves the file pointer to the end
of the string. Here is a PHP script example on how to use fwrite():
<?php
$file = fopen("/temp/todo.txt", "w");
fwrite($file,"Download PHP scripts at dev.fyicenter.com.\r\n");
fwrite($file,"Download Perl scripts at dev.fyicenter.com.\r\n");
fclose($file);
?>
This script will write the following to the file:
Download PHP scripts at dev.fyicenter.com.
Download Perl scripts at dev.fyicenter.com.
(Continued on next part...)
Part:
1
2
3
4
|