Tools, FAQ, Tutorials:
Issue with "while ($c=fgetc($f))" Loop in PHP
What's Wrong with "while ($c=fgetc($f)) {}" in PHP?
✍: 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():
<?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".
⇒ Reading a File in Binary Mode in PHP
⇐ Reading One Character from a File in PHP
2016-11-27, 2795👍, 0💬
Popular Posts:
How to read RSS validation errors at w3.org? If your RSS feed has errors, the RSS validator at w3.or...
How to use the "set-body" Policy Statement for an Azure API service operation? The "set-body" Policy...
How to create the Hello-3.0.epub package? I have all required files to create Hello-3.0.epub. To cre...
Where to get the detailed description of the json_encode() Function in PHP? Here is the detailed des...
Where to see resource detailed information of my API Management Service on Azure Portal? Once you ha...