Navigation

Php

How to Write to a File with file_put_contents()

Quickly write data to files in PHP using file_put_contents() - the simplest way to save strings, arrays, and objects to disk.

Table Of Contents

Quick Implementation

The issue is needing to write data to files efficiently. You can solve this by using file_put_contents() with appropriate flags:

<?php

// Basic file writing
$data = "Hello, World!\nThis is line 2.";
file_put_contents('output.txt', $data);

// Append to existing file
$newData = "\nAppended line";
file_put_contents('output.txt', $newData, FILE_APPEND | LOCK_EX);

// Write array data as JSON
$users = [
    ['id' => 1, 'name' => 'John', 'email' => 'john@example.com'],
    ['id' => 2, 'name' => 'Jane', 'email' => 'jane@example.com']
];
file_put_contents('users.json', json_encode($users, JSON_PRETTY_PRINT));

// Write CSV data
function writeArrayToCsv(array $data, string $filename): bool {
    if (empty($data)) {
        return false;
    }
    
    $output = fopen('php://temp', 'r+');
    
    // Write header
    fputcsv($output, array_keys($data[0]));
    
    // Write data rows
    foreach ($data as $row) {
        fputcsv($output, $row);
    }
    
    rewind($output);
    $csvContent = stream_get_contents($output);
    fclose($output);
    
    return file_put_contents($filename, $csvContent) !== false;
}

// Configuration file writer
function saveConfig(array $config, string $filename): bool {
    $content = "<?php\n// Auto-generated configuration file\n\nreturn [\n";
    
    foreach ($config as $key => $value) {
        $content .= "    '$key' => " . var_export($value, true) . ",\n";
    }
    
    $content .= "];\n";
    
    return file_put_contents($filename, $content, LOCK_EX) !== false;
}

// Log file writer with timestamp
function writeLog(string $message, string $level = 'INFO', string $logFile = 'app.log'): void {
    $timestamp = date('Y-m-d H:i:s');
    $logEntry = "[$timestamp] [$level] $message\n";
    
    file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
}

// Atomic file writing (safer for concurrent access)
function atomicWrite(string $filename, string $content): bool {
    $tempFile = $filename . '.tmp.' . uniqid();
    
    try {
        if (file_put_contents($tempFile, $content, LOCK_EX) === false) {
            return false;
        }
        
        if (!rename($tempFile, $filename)) {
            unlink($tempFile);
            return false;
        }
        
        return true;
    } catch (Exception $e) {
        if (file_exists($tempFile)) {
            unlink($tempFile);
        }
        throw $e;
    }
}

// Error handling wrapper
function safeFileWrite(string $filename, string $content, int $flags = 0): bool {
    // Ensure directory exists
    $directory = dirname($filename);
    if (!is_dir($directory)) {
        if (!mkdir($directory, 0755, true)) {
            throw new RuntimeException("Cannot create directory: $directory");
        }
    }
    
    // Check permissions
    if (file_exists($filename) && !is_writable($filename)) {
        throw new RuntimeException("File is not writable: $filename");
    }
    
    if (!is_writable($directory)) {
        throw new RuntimeException("Directory is not writable: $directory");
    }
    
    $result = file_put_contents($filename, $content, $flags);
    
    if ($result === false) {
        throw new RuntimeException("Failed to write to file: $filename");
    }
    
    return true;
}

// Usage examples
try {
    // Write simple text
    file_put_contents('data/output.txt', 'Sample content');
    
    // Save user data as JSON
    $userData = ['name' => 'John', 'age' => 30];
    file_put_contents('data/user.json', json_encode($userData));
    
    // Append to log
    writeLog('User logged in', 'INFO');
    writeLog('Failed login attempt', 'WARNING');
    
    // Write CSV
    $csvData = [
        ['name' => 'John', 'age' => 30, 'city' => 'New York'],
        ['name' => 'Jane', 'age' => 25, 'city' => 'Los Angeles']
    ];
    writeArrayToCsv($csvData, 'data/users.csv');
    
    // Save configuration
    $config = [
        'database_host' => 'localhost',
        'database_name' => 'myapp',
        'debug_mode' => false
    ];
    saveConfig($config, 'config/app.php');
    
    // Atomic write for critical data
    atomicWrite('critical-data.txt', 'Important information');
    
} catch (RuntimeException $e) {
    echo "Error: " . $e->getMessage();
}

The Answer

file_put_contents() is the most straightforward way to write files:

  1. Simple Syntax: One function call writes entire content
  2. Automatic Handling: Creates file if it doesn't exist
  3. Flag Support: Control behavior with FILE_APPEND, LOCK_EX
  4. Return Value: Returns bytes written or false on failure

Common Flags:

  • FILE_APPEND - Add to end of file instead of overwriting
  • LOCK_EX - Acquire exclusive lock while writing
  • FILE_USE_INCLUDE_PATH - Search in include path

Best Practices:

  • Use LOCK_EX for concurrent access safety
  • Check return value for error handling
  • Ensure directory permissions before writing
  • Use atomic writes for critical data

This approach handles most file writing needs efficiently and safely.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Php