find-resource-leaks

A knowledge base for detecting resource leaks in PHP code, covering methods to find unclosed file handles, unreleased database connections, unreleased streams, missing finally blocks, and uncleared temporary files.

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 "find-resource-leaks" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-8878e360eda4f2c6fb88c2bde6867b742b543e44133d983ba4943174617cefd3. 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

A knowledge base for detecting resource leaks in PHP code, covering methods to find unclosed file handles, unreleased database connections, unreleased streams, missing finally blocks, and uncleared temporary files.

0 Downloads

Introduction source: third_party · dykyi-roman · 0.0.1 Reference

SkillPi interpretation

Tasks
Detects resource leaks in PHP code. Finds unclosed file handles, database connections not released, streams not freed, missing finally blocks, temporary files not cleaned.
Inputs and outputs
```markdown
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: find-resource-leaks
description: Detects resource leaks in PHP code. Finds unclosed file handles, database connections not released, streams not freed, missing finally blocks, temporary files not cleaned.

Resource Leak Detection

Analyze PHP code for resource leak issues.

Detection Patterns

1. Unclosed File Handles

// BUG: File handle not closed
$file = fopen('data.txt', 'r');
$content = fread($file, filesize('data.txt'));
// Missing: fclose($file);

// BUG: Early return without close
$file = fopen($path, 'w');
if (!$valid) {
    return false; // File handle leaked
}
fwrite($file, $data);
fclose($file);

2. Database Connections Not Released

// BUG: Connection not closed
$pdo = new PDO($dsn, $user, $pass);
$stmt = $pdo->query($sql);
// PDO not unset, may hold connection

// BUG: In connection pool context
$connection = $pool->acquire();
$result = $connection->query($sql);
if ($error) {
    throw new Exception(); // Connection leaked
}
$pool->release($connection);

3. Streams Not Freed

// BUG: Stream not closed
$stream = fopen('php://temp', 'r+');
fwrite($stream, $data);
// Missing: fclose($stream);

// BUG: cURL handle not closed
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
// Missing: curl_close($ch);

4. Missing Finally Blocks

// BUG: No finally for cleanup
$lock = $this->acquireLock();
try {
    $this->process();
} catch (Exception $e) {
    $this->log($e);
    throw $e; // Lock not released on exception
}
$this->releaseLock($lock);

// FIXED:
$lock = $this->acquireLock();
try {
    $this->process();
} finally {
    $this->releaseLock($lock);
}

5. Temporary Files Not Cleaned

// BUG: Temp file not deleted
$tempFile = tempnam(sys_get_temp_dir(), 'prefix_');
file_put_contents($tempFile, $data);
$result = $this->processFile($tempFile);
// Missing: unlink($tempFile);

// BUG: Early return leaves temp file
$temp = tmpfile();
if (!$valid) {
    return null; // Temp file not cleaned
}

6. Socket/Network Resources

// BUG: Socket not closed
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, $host, $port);
$data = socket_read($socket, 1024);
// Missing: socket_close($socket);

// BUG: SSH connection not closed
$connection = ssh2_connect($host);
ssh2_auth_password($connection, $user, $pass);
$stream = ssh2_exec($connection, $command);
// Resources not freed

7. Image/GD Resources

// BUG: Image resource not destroyed
$image = imagecreatefromjpeg($path);
$resized = imagescale($image, 100, 100);
imagejpeg($resized, $output);
// Missing: imagedestroy($image); imagedestroy($resized);

8. Doctrine/ORM Resources

// BUG: Large result set in memory
$query = $em->createQuery('SELECT u FROM User u');
$users = $query->getResult(); // All in memory

// BUG: Detached entities not cleared
foreach ($largeDataset as $data) {
    $entity = new Entity($data);
    $em->persist($entity);
    $em->flush();
    // Missing: $em->clear(); for large batches
}

Grep Patterns

# fopen without fclose
Grep: "fopen\([^)]+\)" --glob "**/*.php"
Grep: "fclose\(" --glob "**/*.php"

# curl_init without curl_close
Grep: "curl_init\(" --glob "**/*.php"
Grep: "curl_close\(" --glob "**/*.php"

# try without finally
Grep: "try\s*\{[^}]+\}\s*catch" --glob "**/*.php"

# tempnam/tmpfile usage
Grep: "(tempnam|tmpfile)\(" --glob "**/*.php"

Severity Classification

Pattern Severity
Database connection leak 🔴 Critical
File handle in loop 🔴 Critical
Lock not released 🔴 Critical
Single file handle 🟠 Major
Temp file not cleaned 🟠 Major
Image resource 🟡 Minor

Best Practices

Use try-finally

$resource = acquire();
try {
    process($resource);
} finally {
    release($resource);
}

Use Context Managers (PHP 8.1+)

// Custom destructor-based cleanup
$file = new FileHandler($path);
// Automatically closed on unset/scope exit

Use Transactions Properly

$connection->beginTransaction();
try {
    $this->process();
    $connection->commit();
} catch (Throwable $e) {
    $connection->rollBack();
    throw $e;
}

Output Format

### Resource Leak: [Description]

**Severity:** 🔴/🟠/🟡
**Location:** `file.php:line`
**Type:** [File Handle|Connection|Stream|Lock|Temp File|...]

**Issue:**
Resource acquired but not properly released.

**Code:**
```php
// Problematic code

Fix:

// With proper cleanup

Current listing version

0.0.1

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value85/100

Highlights

  • 提供 PHP 代码资源泄漏检测能力,覆盖文件句柄、数据库连接、流、锁、临时文件等关键场景
  • 适用于开发者在代码审查或静态分析中识别潜在资源泄漏问题,具有明确的实用价值
Trigger Precision95/100

Highlights

  • description 明确描述了功能并列举了具体检测类型,触发词清晰完整,边界明确
Structure and Standards90/100

Highlights

  • 文档结构清晰,包含多个检测模式、grep 模式、严重性分类、最佳实践和输出格式
  • 每部分有代码示例和说明,frontmatter 完整,单文件未超限
Execution Reliability85/100

Highlights

  • 内容为静态分析指南,逻辑完整,提供了可靠的检测模式和修复建议,无执行失败风险
Evidence Verifiability (mean of the first four)89/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.