Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Tmpfile Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require mikehaertl/php-tmpfile
    

    No additional configuration is required—just autoload via Composer.

  2. 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
    
  3. Where to Look First

    • Class Documentation (GitHub).
    • Tmpfile class methods: write(), read(), getPath(), delete(), getContents(), and new ignoreUserAbort().
    • Check tmpfile PHP function behavior for context (this package wraps it).

Implementation Patterns

Core Workflows

  1. Temporary File Handling Use Tmpfile for:

    • Processing file uploads before saving to permanent storage.
    • Generating temporary logs or cache files.
    • Passing data between services without disk I/O overhead.
    $tmpfile = new Tmpfile();
    $tmpfile->write(file_get_contents('input.pdf'));
    // Process $tmpfile->getPath() in a CLI command or queue job
    
  2. Integration with Laravel

    • File Uploads: Replace storage_path('tmp') with Tmpfile for ephemeral uploads.
      $tmpfile = new Tmpfile();
      $tmpfile->write($request->file('document')->getContent());
      // Process or validate $tmpfile->getPath()
      
    • Artisan Commands: Use for temporary file generation in CLI tasks.
      $tmpfile = new Tmpfile();
      $tmpfile->write(json_encode($data));
      $this->info("Temporary file created at: {$tmpfile->getPath()}");
      
  3. 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
    }
    
  4. 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);
    
  5. 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
    

Gotchas and Tips

Pitfalls

  1. File Permissions

    • Temporary files are created in the system’s default temp directory (e.g., /tmp on Linux).
    • Ensure your Laravel app has write permissions in the target environment.
    • Fix: Explicitly set a custom temp directory if needed (see Extension Points).
  2. 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).
    • Workaround: Use fopen() + flock() for true streaming if memory is constrained.
  3. Race Conditions

    • If multiple processes access the same Tmpfile path (unlikely but possible in shared environments), use unique prefixes:
      $tmpfile = new Tmpfile(uniqid('prefix_', true));
      
  4. Laravel Caching

    • Avoid storing Tmpfile objects in Laravel’s cache (e.g., Redis). The path becomes invalid after the object is destroyed.
    • Tip: Serialize only the file contents ($tmpfile->getContents()), not the object.
  5. Premature User Abort (New in 1.3.0)

    • By default, ignoreUserAbort is false. If you enable it ($tmpfile->ignoreUserAbort(true)), ensure your script can handle the forced deletion logic, especially in long-running processes.
    • Warning: This may interfere with expected behavior in some edge cases (e.g., partial writes).

Debugging

  • 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!");
        }
    });
    

Config Quirks

  • No Built-in Config: The package uses PHP’s default tmpfile() behavior. To customize:
    $tmpfile = new Tmpfile(null, 0644, true); // Mode 0644 (rw-r--r--), ignoreUserAbort=true
    
    • First Argument: Custom temp directory (e.g., storage_path('app/tmp')).
    • Second Argument: File permissions (octal).
    • Third Argument: ignoreUserAbort flag (boolean, new in 1.3.0).

Extension Points

  1. 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'));
    });
    
  2. 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());
            });
        }
    }
    
  3. 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!
    
  4. 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;
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
bugban/php-sdk
littlerocket/job-queue-bundle
graham-campbell/flysystem
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
directorytree/opensearch-client
directorytree/opensearch-adapter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php