Navigation

Php

Php How to Work with Temporary Files

Create, manage, and clean up temporary files in PHP safely using tmpfile(), sys_get_temp_dir(), and proper file handling techniques.

Table Of Contents

Implementation

<?php

// Create temporary file with automatic cleanup
$tempFile = tmpfile();
fwrite($tempFile, "Temporary data");
rewind($tempFile);
$content = fread($tempFile, 1024);
// File automatically deleted when $tempFile goes out of scope

// Create named temporary file
$tempPath = tempnam(sys_get_temp_dir(), 'myapp_');
file_put_contents($tempPath, 'Some data');
echo "Temp file: $tempPath\n";
// Remember to unlink($tempPath) when done

// Safe temporary file creation
function createTempFile(string $prefix = 'php_temp_', string $suffix = ''): array {
    $tempDir = sys_get_temp_dir();
    $tempPath = tempnam($tempDir, $prefix);
    
    if ($tempPath === false) {
        throw new RuntimeException('Cannot create temporary file');
    }
    
    // Add suffix if needed
    if ($suffix) {
        $newPath = $tempPath . $suffix;
        if (!rename($tempPath, $newPath)) {
            unlink($tempPath);
            throw new RuntimeException('Cannot rename temporary file');
        }
        $tempPath = $newPath;
    }
    
    return [
        'path' => $tempPath,
        'handle' => fopen($tempPath, 'w+'),
        'cleanup' => function() use ($tempPath) {
            if (file_exists($tempPath)) {
                unlink($tempPath);
            }
        }
    ];
}

// Temporary file manager class
class TempFileManager {
    private array $tempFiles = [];
    
    public function create(string $prefix = 'temp_', string $content = ''): string {
        $path = tempnam(sys_get_temp_dir(), $prefix);
        
        if ($content) {
            file_put_contents($path, $content);
        }
        
        $this->tempFiles[] = $path;
        return $path;
    }
    
    public function createWithExtension(string $extension, string $content = ''): string {
        $path = $this->create('temp_') . '.' . ltrim($extension, '.');
        $tempPath = tempnam(sys_get_temp_dir(), 'temp_');
        
        if (!rename($tempPath, $path)) {
            unlink($tempPath);
            throw new RuntimeException('Cannot create temp file with extension');
        }
        
        if ($content) {
            file_put_contents($path, $content);
        }
        
        $this->tempFiles[] = $path;
        return $path;
    }
    
    public function cleanup(): void {
        foreach ($this->tempFiles as $file) {
            if (file_exists($file)) {
                unlink($file);
            }
        }
        $this->tempFiles = [];
    }
    
    public function __destruct() {
        $this->cleanup();
    }
}

// Process large file using temporary chunks
function processLargeFileInChunks(string $sourceFile, callable $processor): void {
    $tempManager = new TempFileManager();
    $chunkSize = 1024 * 1024; // 1MB chunks
    
    $sourceHandle = fopen($sourceFile, 'rb');
    if (!$sourceHandle) {
        throw new RuntimeException("Cannot open source file: $sourceFile");
    }
    
    $chunkIndex = 0;
    
    while (!feof($sourceHandle)) {
        $chunk = fread($sourceHandle, $chunkSize);
        if ($chunk === false) break;
        
        // Create temporary file for chunk
        $tempFile = $tempManager->create("chunk_{$chunkIndex}_");
        file_put_contents($tempFile, $chunk);
        
        // Process chunk
        $processor($tempFile, $chunkIndex);
        
        $chunkIndex++;
    }
    
    fclose($sourceHandle);
    // Temporary files automatically cleaned up
}

// CSV processing with temporary files
function processCSVWithTemp(string $csvFile): array {
    $tempManager = new TempFileManager();
    $results = [];
    
    // Create temporary file for processed data
    $processedFile = $tempManager->createWithExtension('csv');
    $processedHandle = fopen($processedFile, 'w');
    
    $sourceHandle = fopen($csvFile, 'r');
    $header = fgetcsv($sourceHandle);
    
    // Write header to temp file
    fputcsv($processedHandle, array_merge($header, ['processed_at']));
    
    while (($row = fgetcsv($sourceHandle)) !== false) {
        // Process row data
        $row[] = date('Y-m-d H:i:s');
        fputcsv($processedHandle, $row);
        $results[] = $row;
    }
    
    fclose($sourceHandle);
    fclose($processedHandle);
    
    return $results;
}

// Download and process remote file
function downloadAndProcess(string $url, callable $processor): mixed {
    $tempManager = new TempFileManager();
    
    // Create temporary file for download
    $tempFile = $tempManager->create('download_');
    
    // Download to temporary file
    $downloadHandle = fopen($tempFile, 'w');
    $sourceHandle = fopen($url, 'r');
    
    if (!$sourceHandle) {
        throw new RuntimeException("Cannot open URL: $url");
    }
    
    stream_copy_to_stream($sourceHandle, $downloadHandle);
    fclose($sourceHandle);
    fclose($downloadHandle);
    
    // Process the downloaded file
    return $processor($tempFile);
}

// Usage examples
try {
    // Basic temporary file
    $temp = createTempFile('myapp_', '.txt');
    fwrite($temp['handle'], 'Hello temporary world!');
    fclose($temp['handle']);
    echo "Created: {$temp['path']}\n";
    $temp['cleanup'](); // Clean up when done
    
    // Using temporary file manager
    $manager = new TempFileManager();
    
    $csvTemp = $manager->createWithExtension('csv', "name,email\nJohn,john@example.com");
    $jsonTemp = $manager->createWithExtension('json', json_encode(['test' => true]));
    
    echo "CSV temp: $csvTemp\n";
    echo "JSON temp: $jsonTemp\n";
    
    // Process large file in chunks
    processLargeFileInChunks('large_file.txt', function($chunkFile, $index) {
        echo "Processing chunk $index: " . filesize($chunkFile) . " bytes\n";
        // Process chunk data here
    });
    
    // Download and process
    $result = downloadAndProcess('https://example.com/data.json', function($tempFile) {
        return json_decode(file_get_contents($tempFile), true);
    });
    
    // Automatic cleanup when $manager goes out of scope
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

// Temporary directory operations
function createTempDirectory(string $prefix = 'php_temp_dir_'): string {
    $tempDir = sys_get_temp_dir();
    
    do {
        $tempPath = $tempDir . DIRECTORY_SEPARATOR . $prefix . uniqid();
    } while (file_exists($tempPath));
    
    if (!mkdir($tempPath, 0700)) {
        throw new RuntimeException('Cannot create temporary directory');
    }
    
    return $tempPath;
}

// Clean up old temporary files
function cleanupOldTempFiles(int $olderThanHours = 24): int {
    $tempDir = sys_get_temp_dir();
    $cutoffTime = time() - ($olderThanHours * 3600);
    $deletedCount = 0;
    
    $files = glob($tempDir . DIRECTORY_SEPARATOR . 'php_temp_*');
    
    foreach ($files as $file) {
        if (filemtime($file) < $cutoffTime) {
            if (is_file($file)) {
                unlink($file);
                $deletedCount++;
            } elseif (is_dir($file)) {
                rmdir($file);
                $deletedCount++;
            }
        }
    }
    
    return $deletedCount;
}

Why This Works

Temporary file handling provides safe, efficient data processing:

  1. Automatic Cleanup: tmpfile() automatically removes files when closed
  2. System Integration: Uses OS temporary directory for proper placement
  3. Memory Efficiency: Process large data without loading into RAM
  4. Security: Temporary files have restricted permissions by default

Key Functions:

  • tmpfile() - Creates anonymous temporary file
  • tempnam() - Creates named temporary file
  • sys_get_temp_dir() - Gets system temp directory
  • unlink() - Manually delete temporary files

Best Practices:

  • Always clean up named temporary files
  • Use unique prefixes to avoid conflicts
  • Set proper permissions for security
  • Consider using temporary file managers for complex operations

Perfect for data processing, file uploads, downloads, and any operation requiring temporary storage without cluttering the filesystem.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Php