Navigation

Php

How to Check if a File Exists with file_exists()

Safely verify file existence in PHP before performing operations to prevent errors and handle missing files gracefully.

Table Of Contents

The Fix

<?php

// Basic file existence check
if (file_exists('/path/to/file.txt')) {
    echo "File exists!";
    $content = file_get_contents('/path/to/file.txt');
} else {
    echo "File not found";
}

// Check before writing to avoid overwriting
$filename = 'important-data.json';
if (file_exists($filename)) {
    // Create backup before overwriting
    copy($filename, $filename . '.backup');
}
file_put_contents($filename, json_encode($data));

// Safer file operations with existence check
function safeFileRead(string $filepath): string|null {
    if (!file_exists($filepath)) {
        return null;
    }
    
    if (!is_readable($filepath)) {
        throw new RuntimeException("File exists but is not readable: $filepath");
    }
    
    return file_get_contents($filepath);
}

// Check multiple files
$requiredFiles = ['config.php', 'database.php', 'routes.php'];
$missingFiles = [];

foreach ($requiredFiles as $file) {
    if (!file_exists($file)) {
        $missingFiles[] = $file;
    }
}

if (!empty($missingFiles)) {
    die("Missing required files: " . implode(', ', $missingFiles));
}

// File vs Directory distinction
$path = '/some/path';
if (file_exists($path)) {
    if (is_file($path)) {
        echo "It's a file";
        echo "Size: " . filesize($path) . " bytes";
    } elseif (is_dir($path)) {
        echo "It's a directory";
        echo "Contents: " . count(scandir($path)) - 2 . " items";
    }
}

// Configuration file loading pattern
function loadConfig(string $configFile = 'config.php'): array {
    $defaultConfig = [
        'debug' => false,
        'database' => 'localhost'
    ];
    
    if (!file_exists($configFile)) {
        return $defaultConfig;
    }
    
    $userConfig = include $configFile;
    return array_merge($defaultConfig, $userConfig);
}

// File age check combined with existence
function isFileExpired(string $filepath, int $maxAgeHours = 24): bool {
    if (!file_exists($filepath)) {
        return true; // Consider non-existent files as expired
    }
    
    $fileAge = time() - filemtime($filepath);
    return $fileAge > ($maxAgeHours * 3600);
}

// Usage examples
$config = loadConfig(); // Uses default if config.php doesn't exist

if (isFileExpired('cache/data.json', 2)) {
    // Regenerate cache if file is missing or older than 2 hours
    generateCache();
}

Why This Works

file_exists() is essential for robust file handling:

  1. Prevents Errors: Avoid "file not found" fatal errors
  2. Conditional Logic: Different behavior based on file presence
  3. Universal Check: Works for files, directories, and symlinks
  4. Performance: Fast check before expensive file operations

Important Notes:

  • Returns true for files, directories, and symlinks
  • Use is_file() to check specifically for files
  • Use is_dir() to check specifically for directories
  • Combine with is_readable() for permission checks

Always check file existence before reading, and consider what should happen when files are missing.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Php