check-file-io

审计 PHP 代码中的文件 I/O 模式,检测将整个文件读入内存、缺少文件锁、临时文件未清理、未使用流式处理以及不安全的文件操作等问题。

仓库最近推送
GitHub Stars
109
Forks
26
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "check-file-io":https://skillpi.com/zh/skills/deepskill-e2503d4394e953d6da1eda4d3b26751fd31987a463b4766198ddc0356fe0c5e0。安装前核对上游来源和版本:https://github.com/dykyi-roman/awesome-claude-code。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

审计 PHP 代码中的文件 I/O 模式,检测将整个文件读入内存、缺少文件锁、临时文件未清理、未使用流式处理以及不安全的文件操作等问题。

0 下载

介绍来源: third_party · dykyi-roman · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
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)

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值95/100

亮点

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

亮点

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

亮点

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

亮点

  • 工具来源明确,参数正确,覆盖主要异常场景
  • 提供完整的修复示例和最佳实践,执行可靠性高
证据可验 (前四项均值)93/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

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

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。