1.2.1237. Unchecked Resources

Resources are created, but never checked before being used. This is not safe.

Always check that resources are correctly created before using them.

<?php

// always check that the resource is created correctly
$fp = fopen($d,'r');
if ($fp === false) {
    throw new Exception('File not found');
}
$firstLine = fread($fp);

// This directory is not checked : the path may not exist and return false
$uncheckedDir = opendir($pathToDir);
while(readdir($uncheckedDir)) {
    // do something()
}

// This file is not checked : the path may not exist or be unreadable and return false
$fp = fopen($pathToFile);
while($line = freads($fp)) {
    $text .= $line;
}

// unsafe one-liner : using bzclose on an unchecked resource
bzclose(bzopen('file'));

?>

See also resources.

1.2.1237.1. Suggestions

  • Add a check between the resource acquisition and its usage

1.2.1237.2. Specs

Short name

Structures/UncheckedResources

Rulesets

All, Analyze, CE, CI-checks

Exakat since

0.8.4

PHP Version

All

Severity

Major

Time To Fix

Slow (1 hour)

Precision

High

Features

resource

ClearPHP

no-unchecked-resources

Available in

Entreprise Edition, Community Edition, Exakat Cloud