PHPackages                             vldmir/laravel-temp-file-manager - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. vldmir/laravel-temp-file-manager

ActiveLibrary

vldmir/laravel-temp-file-manager
================================

A Laravel package for managing temporary files with automatic cleanup

v1.1.0(1y ago)02MITPHPPHP ^8.0

Since Nov 15Pushed 1y ago1 watchersCompare

[ Source](https://github.com/vldmir/laravel-temp-file-manager)[ Packagist](https://packagist.org/packages/vldmir/laravel-temp-file-manager)[ RSS](/packages/vldmir-laravel-temp-file-manager/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (3)Versions (3)Used By (0)

Laravel Temporary File Manager
==============================

[](#laravel-temporary-file-manager)

A Laravel package for managing temporary files with automatic cleanup functionality. This package helps you manage temporary files in your Laravel application with features like automatic cleanup, file registration, and scheduled deletion of old files.

[![Latest Version on Packagist](https://camo.githubusercontent.com/ee791ead451cde56524b1d9f43aea79470a3ea69d1a18d535018f14e6036ab6d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f766c646d69722f6c61726176656c2d74656d702d66696c652d6d616e616765722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/vldmir/laravel-temp-file-manager)[![Total Downloads](https://camo.githubusercontent.com/7fa6471c0610dda0bb0005f1626061d654a7ad302453ba592df5c494fe4392ce/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f766c646d69722f6c61726176656c2d74656d702d66696c652d6d616e616765722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/vldmir/laravel-temp-file-manager)

Features
--------

[](#features)

- 🚀 Easy temporary file management
- 💾 Multiple methods for saving temporary files
- 🧹 Automatic cleanup of old files
- 🗑️ Auto-deletion of registered files after process completion
- ⚙️ Configurable storage location and retention period
- 📦 Laravel integration with Facade support
- 🔄 Scheduled cleanup command
- 💪 Strong typing and modern PHP 8.0+ features

Requirements
------------

[](#requirements)

- PHP 8.0 or higher
- Laravel 8.0 or higher

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require vldmir/laravel-temp-file-manager
```

Configuration
-------------

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --provider="Vldmir\TempFileManager\TempFileManagerServiceProvider" --tag="config"
```

This will create a `temp-file-manager.php` config file in your config directory. You can modify these settings:

```
return [
    'directory' => 'temp',
    'max_age_hours' => 10,
    'disk' => 'local',
];
```

Usage
-----

[](#usage)

### Saving Files

[](#saving-files)

The package provides several methods to save files to temporary storage:

#### 1. Save String Content

[](#1-save-string-content)

```
// Save string content
$content = "Hello, World!";
$tempPath = TempManager::save($content, 'hello.txt');

// Save with auto-generated filename
$tempPath = TempManager::save($content);
```

#### 2. Save Uploaded Files

[](#2-save-uploaded-files)

```
// In your controller
public function upload(Request $request)
{
    // Save uploaded file with original name
    $tempPath = TempManager::saveUploadedFile($request->file('document'));

    // Save with custom filename
    $tempPath = TempManager::saveUploadedFile(
        $request->file('document'),
        'custom-name.pdf'
    );
}
```

#### 3. Save From URL

[](#3-save-from-url)

```
// Download and save file from URL
try {
    $tempPath = TempManager::saveFromUrl('https://example.com/file.pdf');

    // With custom filename
    $tempPath = TempManager::saveFromUrl(
        'https://example.com/file.pdf',
        'local-copy.pdf'
    );
} catch (\Exception $e) {
    // Handle download error
}
```

#### 4. Save Stream/Resource

[](#4-save-streamresource)

```
// Save from resource
$handle = fopen('path/to/file', 'r');
$tempPath = TempManager::save($handle, 'output.txt');
fclose($handle);
```

### File Cleanup Behavior

[](#file-cleanup-behavior)

There are three ways files can be cleaned up:

1. **Automatic Cleanup After Process** (Using register)

```
// The file will be automatically deleted when the PHP process ends
$tempPath = TempManager::getTempPath('upload.txt');
TempManager::register($tempPath);

// Do your work with the file
// ...
// File will be deleted automatically after process completion
```

2. **Manual Cleanup** (Using cleanup method)

```
// Manually delete when you're done
TempManager::cleanup($tempPath);
```

3. **Scheduled Cleanup** (For old files)

```
// All files older than max_age_hours will be removed
TempManager::cleanupOldFiles();
```

### Scheduled Cleanup Command

[](#scheduled-cleanup-command)

To automatically clean up old temporary files, register the cleanup command in your `App\Console\Kernel`:

```
protected function schedule(Schedule $schedule)
{
    $schedule->command('temp-files:cleanup')->hourly();
}
```

### Dependency Injection Usage

[](#dependency-injection-usage)

You can also use dependency injection to access the TempFileManager:

```
use Vldmir\TempFileManager\TempFileManager;

class MyController extends Controller
{
    public function __construct(private TempFileManager $tempManager)
    {
        $this->tempManager = $tempManager;
    }

    public function store(Request $request)
    {
        $tempPath = $this->tempManager->getTempPath('uploaded-file.txt');
        $this->tempManager->register($tempPath);
        // File will be auto-cleaned after process ends
    }
}
```

### Complete Example in Controller

[](#complete-example-in-controller)

```
class DocumentController extends Controller
{
    public function store(Request $request)
    {
        try {
            // Save uploaded file
            $tempPath = TempManager::saveUploadedFile($request->file('document'));

            // Process the file
            // ...

            // Optionally clean up early if you're done
            TempManager::cleanup($tempPath);

            return response()->json(['success' => true]);

        } catch (\Exception $e) {
            // File will be auto-cleaned up when process ends
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    public function download()
    {
        try {
            // Save remote file temporarily
            $tempPath = TempManager::saveFromUrl('https://example.com/document.pdf');

            // Process or serve the file
            return response()->download($tempPath);
            // File will be cleaned up after response is sent

        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}
```

### File Naming Behavior

[](#file-naming-behavior)

When saving files, the package handles filenames in the following way:

1. If no filename is provided, a random name is generated
2. If a filename is provided:
    - Unsafe characters are removed from the filename
    - If a file with the same name exists, a counter is appended (e.g., `file_1.txt`, `file_2.txt`)

```
// Examples of filename handling
$manager = app(TempFileManager::class);

// With custom filename (unsafe characters are removed)
$path = $manager->save($content, 'my/unsafe:file.txt');
// Results in: my_unsafe_file.txt

// With duplicate filename
$path1 = $manager->save($content1, 'report.pdf');
$path2 = $manager->save($content2, 'report.pdf');
// Results in: report.pdf, report_1.pdf

// With uploaded file
$path = $manager->saveUploadedFile($uploadedFile, 'custom-name.pdf');
// Uses the provided name, sanitized if necessary

// Without filename
$path = $manager->save($content);
// Generates a random filename
```

The filename sanitization process:

- Removes any character that isn't alphanumeric, dot, dash, or underscore
- Replaces multiple consecutive dots/underscores with a single one
- Removes dots and dashes from the start and end of the filename
- Ensures the filename isn't empty

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

### Security

[](#security)

If you discover any security-related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Vladimir](https://github.com/vldmir)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

25

—

LowBetter than 37% of packages

Maintenance38

Infrequent updates — may be unmaintained

Popularity2

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

2

Last Release

542d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/28f2149d7afc88386ce2e51326341863bc9b3088ee551269ef76bfd23981d548?d=identicon)[vldmir](/maintainers/vldmir)

---

Top Contributors

[![vldmir](https://avatars.githubusercontent.com/u/22792951?v=4)](https://github.com/vldmir "vldmir (5 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/vldmir-laravel-temp-file-manager/health.svg)

```
[![Health](https://phpackages.com/badges/vldmir-laravel-temp-file-manager/health.svg)](https://phpackages.com/packages/vldmir-laravel-temp-file-manager)
```

###  Alternatives

[fumeapp/modeltyper

Generate TypeScript interfaces from Laravel Models

196277.9k](/packages/fumeapp-modeltyper)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
