What's Wrong with "while ($c=fgetc($f)) {}"


What's Wrong with "while ($c=fgetc($f)) {}"? - PHP Script Tips - Reading and Writing Files

✍: FYIcenter.com


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():

$file = fopen("/temp/cgi.log", "w");
fwrite($file,"Remote host:\r\n");
fwrite($file,"Query string: cate=102&order=down&lang=en.\r\n");

$file = fopen("/temp/cgi.log", "r");
while ( ($char=fgetc($file)) ) {

This script will print:

Remote host:

As you can see the loop indeed stopped at character "0".

2007-04-22, 4726👍, 0💬