Navigation

Php

PHP How to Get File Size and Modification Time

Retrieve essential file metadata using PHP's built-in functions for size, modification time, and other file properties - crucial for file management.

Table Of Contents

Working Code

Here's how to get comprehensive file information efficiently:

<?php

// Basic file size and modification time
$filepath = '/path/to/file.txt';

$size = filesize($filepath);
$modifiedTime = filemtime($filepath);

echo "File size: $size bytes\n";
echo "Last modified: " . date('Y-m-d H:i:s', $modifiedTime) . "\n";

// Comprehensive file information function
function getFileInfo(string $filepath): array {
    if (!file_exists($filepath)) {
        throw new InvalidArgumentException("File does not exist: $filepath");
    }
    
    return [
        'path' => $filepath,
        'name' => basename($filepath),
        'size' => filesize($filepath),
        'size_formatted' => formatFileSize(filesize($filepath)),
        'modified_timestamp' => filemtime($filepath),
        'modified_date' => date('Y-m-d H:i:s', filemtime($filepath)),
        'accessed_timestamp' => fileatime($filepath),
        'accessed_date' => date('Y-m-d H:i:s', fileatime($filepath)),
        'created_timestamp' => filectime($filepath),
        'created_date' => date('Y-m-d H:i:s', filectime($filepath)),
        'is_readable' => is_readable($filepath),
        'is_writable' => is_writable($filepath),
        'permissions' => substr(sprintf('%o', fileperms($filepath)), -4),
        'owner' => fileowner($filepath),
        'group' => filegroup($filepath),
        'type' => filetype($filepath),
        'extension' => pathinfo($filepath, PATHINFO_EXTENSION)
    ];
}

// Format file size for human reading
function formatFileSize(int $bytes, int $precision = 2): string {
    $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
    
    for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
        $bytes /= 1024;
    }
    
    return round($bytes, $precision) . ' ' . $units[$i];
}

// Check if file was modified recently
function isFileRecentlyModified(string $filepath, int $hours = 24): bool {
    if (!file_exists($filepath)) {
        return false;
    }
    
    $modifiedTime = filemtime($filepath);
    $cutoffTime = time() - ($hours * 3600);
    
    return $modifiedTime > $cutoffTime;
}

// Get files by size range
function getFilesBySize(string $directory, int $minSize = 0, int $maxSize = PHP_INT_MAX): array {
    $matchingFiles = [];
    
    if (!is_dir($directory)) {
        return $matchingFiles;
    }
    
    $files = glob($directory . DIRECTORY_SEPARATOR . '*');
    
    foreach ($files as $file) {
        if (is_file($file)) {
            $size = filesize($file);
            if ($size >= $minSize && $size <= $maxSize) {
                $matchingFiles[] = [
                    'path' => $file,
                    'name' => basename($file),
                    'size' => $size,
                    'size_formatted' => formatFileSize($size)
                ];
            }
        }
    }
    
    // Sort by size
    usort($matchingFiles, fn($a, $b) => $b['size'] <=> $a['size']);
    
    return $matchingFiles;
}

// Find files modified within date range
function getFilesModifiedBetween(string $directory, string $startDate, string $endDate): array {
    $startTimestamp = strtotime($startDate);
    $endTimestamp = strtotime($endDate);
    $matchingFiles = [];
    
    if (!is_dir($directory)) {
        return $matchingFiles;
    }
    
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS)
    );
    
    foreach ($iterator as $file) {
        if ($file->isFile()) {
            $modTime = $file->getMTime();
            if ($modTime >= $startTimestamp && $modTime <= $endTimestamp) {
                $matchingFiles[] = [
                    'path' => $file->getPathname(),
                    'name' => $file->getFilename(),
                    'size' => $file->getSize(),
                    'modified' => date('Y-m-d H:i:s', $modTime)
                ];
            }
        }
    }
    
    return $matchingFiles;
}

// Directory size calculation
function getDirectorySize(string $directory): array {
    $totalSize = 0;
    $fileCount = 0;
    $dirCount = 0;
    
    if (!is_dir($directory)) {
        throw new InvalidArgumentException("Not a directory: $directory");
    }
    
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS)
    );
    
    foreach ($iterator as $file) {
        if ($file->isFile()) {
            $totalSize += $file->getSize();
            $fileCount++;
        } else {
            $dirCount++;
        }
    }
    
    return [
        'total_size' => $totalSize,
        'total_size_formatted' => formatFileSize($totalSize),
        'file_count' => $fileCount,
        'directory_count' => $dirCount,
        'average_file_size' => $fileCount > 0 ? $totalSize / $fileCount : 0
    ];
}

// File age analysis
function analyzeFileAge(string $filepath): array {
    if (!file_exists($filepath)) {
        throw new InvalidArgumentException("File does not exist: $filepath");
    }
    
    $modTime = filemtime($filepath);
    $currentTime = time();
    $ageSeconds = $currentTime - $modTime;
    
    return [
        'age_seconds' => $ageSeconds,
        'age_minutes' => round($ageSeconds / 60, 2),
        'age_hours' => round($ageSeconds / 3600, 2),
        'age_days' => round($ageSeconds / 86400, 2),
        'age_weeks' => round($ageSeconds / 604800, 2),
        'age_months' => round($ageSeconds / 2592000, 2),
        'is_recent' => $ageSeconds < 86400, // Less than 1 day
        'is_old' => $ageSeconds > 2592000,  // More than 30 days
    ];
}

// Compare file timestamps
function compareFiles(string $file1, string $file2): array {
    if (!file_exists($file1) || !file_exists($file2)) {
        throw new InvalidArgumentException("One or both files do not exist");
    }
    
    $mtime1 = filemtime($file1);
    $mtime2 = filemtime($file2);
    $size1 = filesize($file1);
    $size2 = filesize($file2);
    
    return [
        'file1' => ['path' => $file1, 'modified' => $mtime1, 'size' => $size1],
        'file2' => ['path' => $file2, 'modified' => $mtime2, 'size' => $size2],
        'newer_file' => $mtime1 > $mtime2 ? $file1 : $file2,
        'larger_file' => $size1 > $size2 ? $file1 : $file2,
        'time_difference' => abs($mtime1 - $mtime2),
        'size_difference' => abs($size1 - $size2),
        'same_size' => $size1 === $size2,
        'same_modification_time' => $mtime1 === $mtime2
    ];
}

// Usage examples
try {
    $testFile = 'example.txt';
    
    // Get comprehensive file info
    $info = getFileInfo($testFile);
    echo "File: {$info['name']}\n";
    echo "Size: {$info['size_formatted']}\n";
    echo "Modified: {$info['modified_date']}\n";
    echo "Permissions: {$info['permissions']}\n\n";
    
    // Check if recently modified
    if (isFileRecentlyModified($testFile, 48)) {
        echo "File was modified in the last 48 hours\n";
    }
    
    // Find large files (over 1MB)
    $largeFiles = getFilesBySize('/path/to/directory', 1048576);
    echo "Found " . count($largeFiles) . " files over 1MB\n";
    
    // Files modified in last week
    $recentFiles = getFilesModifiedBetween('/uploads', '-1 week', 'now');
    echo "Files modified this week: " . count($recentFiles) . "\n";
    
    // Directory size analysis
    $dirStats = getDirectorySize('/var/logs');
    echo "Directory size: {$dirStats['total_size_formatted']}\n";
    echo "Contains {$dirStats['file_count']} files\n";
    
    // File age analysis
    $ageInfo = analyzeFileAge($testFile);
    echo "File is {$ageInfo['age_days']} days old\n";
    
    // Compare two files
    $comparison = compareFiles('file1.txt', 'file2.txt');
    echo "Newer file: " . basename($comparison['newer_file']) . "\n";
    echo "Size difference: " . formatFileSize($comparison['size_difference']) . "\n";
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

Behind the Code

PHP provides several functions for file metadata retrieval:

  1. Size Information: filesize() returns bytes, format for readability
  2. Time Functions: filemtime(), fileatime(), filectime() for different timestamps
  3. Comparative Analysis: Compare files and track changes over time
  4. Batch Operations: Process multiple files efficiently

Essential Functions:

  • filesize() - File size in bytes
  • filemtime() - Last modification time
  • fileatime() - Last access time
  • filectime() - Inode change time
  • date() - Format timestamps for display

Use Cases:

  • File cleanup based on age or size
  • Backup systems that track modifications
  • File browsers with detailed information
  • Performance monitoring of file growth
  • Cache invalidation based on modification time

Critical for any application that manages files and needs to make decisions based on file properties.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Php