1.2.986. Possible Infinite Loop¶
Loops on files that can’t be open results in infinite loop.
fgets(), and functions like fgetss(), fgetcsv(), fread(), return false when they finish reading, or can’t access the file.
In case the file is not accessible, comparing the result of the reading to something that is falsy, leads to a permanent valid condition. The execution will only finish when the max_execution_time
is reached.
It is recommended to check the file resources when they are opened, and always use === or !== to compare readings. feof() is also a reliable function here.
<?php
$file = fopen('/path/to/file.txt', 'r');
// when fopen() fails, the next loops is infinite
// fgets() will always return false, and while will always be true.
while($line = fgets($file) != 'a') {
doSomething();
}
?>
1.2.986.1. Connex PHP features¶
1.2.986.1.1. Suggestions¶
Add a check before using the result of the method.
Add a counter to break the loop after a limit of loops.
1.2.986.1.2. Specs¶
Short name |
Structures/PossibleInfiniteLoop |
Rulesets |
|
Exakat since |
1.1.5 |
PHP Version |
All |
Severity |
Critical |
Time To Fix |
Quick (30 mins) |
Precision |
Very high |
Available in |