1.2.980. 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.980.1. Specs

Short name

Structures/PossibleInfiniteLoop

Rulesets

All, Analyze

Exakat since

1.1.5

PHP Version

All

Severity

Critical

Time To Fix

Quick (30 mins)

Precision

Very high

Features

loop

Available in

Entreprise Edition, Exakat Cloud