mikehaertl/php-tmpfile
Create and manage secure temporary files in PHP with an object-oriented API. php-tmpfile handles creation, automatic cleanup, and safe paths across platforms—ideal for generating intermediate output, working with CLI tools, or handling uploads without manual temp file housekeeping.
Installation
composer require mikehaertl/php-tmpfile
No additional configuration is required—just autoload via Composer.
First Use Case Create a temporary file for processing uploads or logs:
use MikeHaertl\PhpTmpfile\Tmpfile;
$tmpfile = new Tmpfile();
$tmpfile->write('Hello, temporary file!');
$content = $tmpfile->read();
$tmpfile->delete(); // Auto-deletes on object destruction if not manually deleted
Where to Look First
Tmpfile class methods: write(), read(), getPath(), delete(), getContents(), and new ignoreUserAbort().tmpfile PHP function behavior for context (this package wraps it).Temporary File Handling
Use Tmpfile for:
$tmpfile = new Tmpfile();
$tmpfile->write(file_get_contents('input.pdf'));
// Process $tmpfile->getPath() in a CLI command or queue job
Integration with Laravel
storage_path('tmp') with Tmpfile for ephemeral uploads.
$tmpfile = new Tmpfile();
$tmpfile->write($request->file('document')->getContent());
// Process or validate $tmpfile->getPath()
$tmpfile = new Tmpfile();
$tmpfile->write(json_encode($data));
$this->info("Temporary file created at: {$tmpfile->getPath()}");
Context Managers
Leverage PHP’s __destruct() to auto-delete files:
$tmpfile = new Tmpfile();
try {
$tmpfile->write($data);
// Critical section
} finally {
// File auto-deletes here if not manually deleted
}
Streaming Large Files
Use Tmpfile to stream chunks without loading entire files into memory:
$tmpfile = new Tmpfile();
$handle = fopen($tmpfile->getPath(), 'w');
foreach ($largeData as $chunk) {
fwrite($handle, $chunk);
}
fclose($handle);
Handling Premature User Disconnections (New in 1.3.0)
Use ignoreUserAbort() to ensure temporary files are deleted even if the user closes the connection (e.g., for long-running scripts or CLI processes):
$tmpfile = new Tmpfile();
$tmpfile->ignoreUserAbort(true); // Force deletion on user abort
$tmpfile->write($data);
// File will be deleted even if the script is interrupted
File Permissions
/tmp on Linux).Memory vs. Disk Trade-offs
Tmpfile uses tmpfile() under the hood, which may not be ideal for very large files (PHP’s memory_limit can still be hit during reads/writes).fopen() + flock() for true streaming if memory is constrained.Race Conditions
Tmpfile path (unlikely but possible in shared environments), use unique prefixes:
$tmpfile = new Tmpfile(uniqid('prefix_', true));
Laravel Caching
Tmpfile objects in Laravel’s cache (e.g., Redis). The path becomes invalid after the object is destroyed.$tmpfile->getContents()), not the object.Premature User Abort (New in 1.3.0)
ignoreUserAbort is false. If you enable it ($tmpfile->ignoreUserAbort(true)), ensure your script can handle the forced deletion logic, especially in long-running processes.Verify File Existence:
if (!file_exists($tmpfile->getPath())) {
throw new \RuntimeException("Temporary file missing!");
}
Check Permissions:
ls -la /tmp # Linux/macOS
Or in PHP:
var_dump(is_writable(sys_get_temp_dir()));
Debugging User Abort Behavior:
$tmpfile = new Tmpfile();
$tmpfile->ignoreUserAbort(true);
register_shutdown_function(function () use ($tmpfile) {
if (!$tmpfile->isDeleted()) {
error_log("Tmpfile was not deleted on shutdown!");
}
});
tmpfile() behavior. To customize:
$tmpfile = new Tmpfile(null, 0644, true); // Mode 0644 (rw-r--r--), ignoreUserAbort=true
storage_path('app/tmp')).ignoreUserAbort flag (boolean, new in 1.3.0).Custom Temp Directory
Override the default temp directory in Laravel’s bootstrap/app.php:
$app->bind(Tmpfile::class, function () {
return new Tmpfile(storage_path('app/tmp'));
});
Event Hooks Extend the class to add pre/post actions:
class CustomTmpfile extends Tmpfile {
public function __construct() {
parent::__construct();
$this->ignoreUserAbort(true); // Enable forced deletion
$this->onDelete(function () {
Log::debug("Deleted temp file: " . $this->getPath());
});
}
}
Symlink Support If you need symlinks to temporary files (e.g., for web access):
$tmpfile = new Tmpfile();
$tmpfile->ignoreUserAbort(true); // Ensure cleanup
$symlinkPath = public_path('tmp/' . basename($tmpfile->getPath()));
symlink($tmpfile->getPath(), $symlinkPath);
// Remember to unlink $symlinkPath when done!
Global ignoreUserAbort Configuration
For Laravel applications, bind a configured instance in AppServiceProvider:
$this->app->singleton(Tmpfile::class, function () {
$tmpfile = new Tmpfile();
$tmpfile->ignoreUserAbort(config('tmpfile.ignore_user_abort', false));
return $tmpfile;
});
How can I help you explore Laravel packages today?