check-file-io

Audit file I/O patterns in PHP code, detecting full-file reads into memory, missing file locks, uncleaned temporary files, lack of stream usage, and unsafe file operations.

Last repository push
GitHub Stars
109
Forks
26
Issues / PRs
1

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "check-file-io" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-e2503d4394e953d6da1eda4d3b26751fd31987a463b4766198ddc0356fe0c5e0. Verify the upstream source and version against https://github.com/dykyi-roman/awesome-claude-code before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Audit file I/O patterns in PHP code, detecting full-file reads into memory, missing file locks, uncleaned temporary files, lack of stream usage, and unsafe file operations.

0 Downloads

Introduction source: third_party · dykyi-roman · 0.0.1 Reference

SkillPi interpretation

Tasks
Audits file I/O patterns in PHP code. Detects full-file reads into memory, missing file locks, temp file cleanup issues, missing stream usage, and insecure file operations.
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: check-file-io
description: Audits file I/O patterns in PHP code. Detects full-file reads into memory, missing file locks, temp file cleanup issues, missing stream usage, and insecure file operations.

File I/O Patterns Audit

Analyze PHP code for suboptimal or dangerous file I/O patterns.

Detection Patterns

1. Full File Read Into Memory

// CRITICAL: Entire file loaded into memory
$content = file_get_contents('/path/to/large-file.csv'); // 500MB file → OOM!
$lines = file('/path/to/large-file.csv'); // Loads all lines into array!

// CRITICAL: Reading large file to process line by line
$content = file_get_contents($path);
$lines = explode("\n", $content); // Double memory: content + lines array
foreach ($lines as $line) {
    $this->process($line);
}

// CORRECT: Stream processing
$handle = fopen($path, 'rb');
while (($line = fgets($handle)) !== false) {
    $this->process(trim($line));
}
fclose($handle);

// CORRECT: Generator for large files
function readLines(string $path): \Generator
{
    $handle = fopen($path, 'rb');
    try {
        while (($line = fgets($handle)) !== false) {
            yield trim($line);
        }
    } finally {
        fclose($handle);
    }
}

2. Missing File Locks

// CRITICAL: Concurrent writes without locking
class FileLogger
{
    public function log(string $message): void
    {
        $handle = fopen($this->path, 'ab');
        fwrite($handle, $message . "\n"); // Race condition with concurrent writers!
        fclose($handle);
    }
}

// CRITICAL: Read-modify-write without lock
$counter = (int) file_get_contents('counter.txt');
$counter++;
file_put_contents('counter.txt', (string) $counter);
// Concurrent requests: both read 5, both write 6 instead of 7

// CORRECT: File locking
$handle = fopen($this->path, 'cb+');
if (flock($handle, LOCK_EX)) {
    $counter = (int) stream_get_contents($handle);
    $counter++;
    ftruncate($handle, 0);
    rewind($handle);
    fwrite($handle, (string) $counter);
    flock($handle, LOCK_UN);
}
fclose($handle);

3. Temp File Not Cleaned Up

// CRITICAL: Temp file created but never deleted
class PdfGenerator
{
    public function generate(array $data): string
    {
        $tmpFile = tempnam(sys_get_temp_dir(), 'pdf_');
        file_put_contents($tmpFile, $this->render($data));
        $pdf = $this->converter->convert($tmpFile);
        // $tmpFile never deleted! Disk fills up over time
        return $pdf;
    }
}

// CORRECT: Always clean up in finally
class PdfGenerator
{
    public function generate(array $data): string
    {
        $tmpFile = tempnam(sys_get_temp_dir(), 'pdf_');
        try {
            file_put_contents($tmpFile, $this->render($data));
            return $this->converter->convert($tmpFile);
        } finally {
            if (file_exists($tmpFile)) {
                unlink($tmpFile);
            }
        }
    }
}

4. Missing File Handle Cleanup

// CRITICAL: File handle not closed on exception
class CsvProcessor
{
    public function process(string $path): array
    {
        $handle = fopen($path, 'rb');
        $results = [];
        while (($row = fgetcsv($handle)) !== false) {
            $results[] = $this->transform($row); // If this throws, handle leaks!
        }
        fclose($handle);
        return $results;
    }
}

// CORRECT: try/finally pattern
class CsvProcessor
{
    public function process(string $path): array
    {
        $handle = fopen($path, 'rb');
        try {
            $results = [];
            while (($row = fgetcsv($handle)) !== false) {
                $results[] = $this->transform($row);
            }
            return $results;
        } finally {
            fclose($handle);
        }
    }
}

5. SplFileObject Not Used for CSV

// ANTIPATTERN: Manual CSV parsing
$handle = fopen($path, 'rb');
$header = fgetcsv($handle);
while ($row = fgetcsv($handle)) {
    $data = array_combine($header, $row);
}
fclose($handle);

// CORRECT: SplFileObject with generator
function readCsv(string $path): \Generator
{
    $file = new \SplFileObject($path, 'rb');
    $file->setFlags(\SplFileObject::READ_CSV | \SplFileObject::SKIP_EMPTY);
    $header = $file->fgetcsv();
    foreach ($file as $row) {
        if ($row === [null]) continue;
        yield array_combine($header, $row);
    }
}

6. Unsafe File Path Construction

// CRITICAL: Path traversal + race condition
$path = '/uploads/' . $request->get('filename');
if (file_exists($path)) {        // Check
    $content = file_get_contents($path); // Use — TOCTOU!
}

// CORRECT: Validate and use realpath
$basePath = realpath('/uploads');
$fullPath = realpath('/uploads/' . basename($request->get('filename')));
if ($fullPath === false || !str_starts_with($fullPath, $basePath)) {
    throw new SecurityException('Invalid file path');
}
$content = file_get_contents($fullPath);

7. Writing Large Output Without Streaming

// CRITICAL: Building entire response in memory
class ExportController
{
    public function export(): Response
    {
        $data = $this->repository->findAll(); // 100K rows
        $csv = '';
        foreach ($data as $row) {
            $csv .= implode(',', $row) . "\n"; // String grows to 500MB
        }
        return new Response($csv);
    }
}

// CORRECT: Streaming response
class ExportController
{
    public function export(): StreamedResponse
    {
        return new StreamedResponse(function () {
            $handle = fopen('php://output', 'wb');
            foreach ($this->repository->findAllIterable() as $row) {
                fputcsv($handle, $row);
                flush();
            }
            fclose($handle);
        }, 200, ['Content-Type' => 'text/csv']);
    }
}

Grep Patterns

# Full file reads
Grep: "file_get_contents\(|file\(" --glob "**/*.php"

# Missing file locks
Grep: "fwrite\(|file_put_contents\(" --glob "**/*.php"
Grep: "flock\(" --glob "**/*.php"

# Temp files
Grep: "tempnam\(|sys_get_temp_dir\(|tmpfile\(" --glob "**/*.php"
Grep: "unlink\(.*tmp" --glob "**/*.php"

# File handles without finally
Grep: "fopen\(" --glob "**/*.php"
Grep: "finally.*fclose" --glob "**/*.php"

# CSV processing
Grep: "fgetcsv\(|SplFileObject" --glob "**/*.php"

# String concatenation for output
Grep: "\\\$.*\.=.*\\\\n|\\\$.*\.= implode" --glob "**/*.php"

Severity Classification

Pattern Severity
Full file read of unbounded size 🔴 Critical
File handle leak on exception 🔴 Critical
Write without lock (shared file) 🟠 Major
Temp file not cleaned up 🟠 Major
Building large string in memory 🟠 Major
Missing SplFileObject for CSV 🟡 Minor

Output Format

### File I/O: [Description]

**Severity:** 🔴/🟠/🟡
**Location:** `file.php:line`
**Impact:** [Memory/Performance/Data integrity]

**Issue:**
[Description of the file I/O problem]

**Code:**
```php
// Problematic pattern

Fix:

// Stream-based / locked / cleaned-up pattern

Expected Improvement: Memory: 500MB → 4KB (streaming)

Current listing version

0.0.1

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value95/100

Highlights

  • PHP文件I/O审计是开发中的高频刚需,直接解决内存溢出、并发安全、资源泄漏等关键问题
  • 覆盖全文件读入内存、文件锁缺失、临时文件清理、流处理等核心场景
  • 提供完整的grep模式和严重性分类,实用性强
Trigger Precision90/100

Highlights

  • description清晰描述功能边界,触发词精准完整
  • 覆盖多种文件I/O模式的变体,边界清晰
Structure and Standards95/100

Highlights

  • Phase/步骤清晰,有完整示例和出口条件
  • frontmatter完整,单文件结构规范,易于理解执行流程
Execution Reliability90/100

Highlights

  • 工具来源明确,参数正确,覆盖主要异常场景
  • 提供完整的修复示例和最佳实践,执行可靠性高
Evidence Verifiability (mean of the first four)93/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.