PHP Filesystem Functions
Introduction to PHP Filesystem Functions
PHP provides a comprehensive set of functions for interacting with the filesystem, including reading and writing files, managing directories, and handling file metadata.
File Operations
Reading Files
<?php
// file_get_contents() - Read entire file into string
$content = file_get_contents('data.txt');
echo $content;
// file() - Read file into array (line by line)
$lines = file('data.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
echo $line . "\n";
}
// fopen(), fread(), fclose() - File handle operations
$handle = fopen('data.txt', 'r');
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
}
// readfile() - Output file directly
readfile('image.jpg'); // Outputs file content to browser
?>
Writing Files
<?php
// file_put_contents() - Write string to file
$data = "Hello, World!";
file_put_contents('output.txt', $data);
// Append to file
file_put_contents('log.txt', "New log entry\n", FILE_APPEND | LOCK_EX);
// Write array to file
$lines = ['Line 1', 'Line 2', 'Line 3'];
file_put_contents('lines.txt', implode("\n", $lines));
// fopen(), fwrite(), fclose() - File handle operations
$handle = fopen('output.txt', 'w');
if ($handle) {
fwrite($handle, "Hello, World!");
fclose($handle);
}
?>
File Information
<?php
$filename = 'document.pdf';
// Check if file exists
if (file_exists($filename)) {
echo "File exists\n";
}
// Get file size
$size = filesize($filename);
echo "File size: " . $size . " bytes\n";
// Get file modification time
$mtime = filemtime($filename);
echo "Last modified: " . date('Y-m-d H:i:s', $mtime) . "\n";
// Get file type
$type = filetype($filename);
echo "File type: " . $type . "\n"; // file, dir, link, etc.
// Check if file is readable/writable
if (is_readable($filename)) {
echo "File is readable\n";
}
if (is_writable($filename)) {
echo "File is writable\n";
}
// Get file permissions
$perms = fileperms($filename);
echo "Permissions: " . substr(sprintf('%o', $perms), -4) . "\n";
?>
Directory Operations
Creating and Removing Directories
<?php
// Create directory
if (!is_dir('uploads')) {
mkdir('uploads', 0755, true); // recursive = true
}
// Create nested directories
mkdir('path/to/nested/dir', 0755, true);
// Remove directory (must be empty)
rmdir('empty_directory');
// Remove directory recursively
function removeDirectory($dir) {
if (!is_dir($dir)) {
return false;
}
$files = array_diff(scandir($dir), ['.', '..']);
foreach ($files as $file) {
$path = $dir . DIRECTORY_SEPARATOR . $file;
is_dir($path) ? removeDirectory($path) : unlink($path);
}
return rmdir($dir);
}
removeDirectory('path/to/directory');
?>
Reading Directories
<?php
// scandir() - Get array of files and directories
$files = scandir('uploads');
foreach ($files as $file) {
if ($file !== '.' && $file !== '..') {
echo $file . "\n";
}
}
// glob() - Find pathnames matching pattern
$phpFiles = glob('*.php');
$allImages = glob('images/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
// DirectoryIterator class
$iterator = new DirectoryIterator('uploads');
foreach ($iterator as $fileinfo) {
if (!$fileinfo->isDot()) {
echo $fileinfo->getFilename() . "\n";
}
}
// RecursiveDirectoryIterator for nested directories
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('project'),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $file) {
if ($file->isFile() && $file->getExtension() === 'php') {
echo $file->getPathname() . "\n";
}
}
?>
Path Manipulation
Path Information
<?php
$path = '/var/www/html/documents/report.pdf';
// Get path components
$info = pathinfo($path);
echo "Directory: " . $info['dirname'] . "\n"; // /var/www/html/documents
echo "Filename: " . $info['filename'] . "\n"; // report
echo "Extension: " . $info['extension'] . "\n"; // pdf
echo "Basename: " . $info['basename'] . "\n"; // report.pdf
// Individual functions
echo "Directory: " . dirname($path) . "\n";
echo "Basename: " . basename($path) . "\n";
echo "Extension: " . pathinfo($path, PATHINFO_EXTENSION) . "\n";
// Real path (resolve symbolic links and relative paths)
$realPath = realpath('../config/database.php');
echo "Real path: " . $realPath . "\n";
?>
Path Building
<?php
// Build paths correctly across platforms
function buildPath(...$segments) {
return implode(DIRECTORY_SEPARATOR, $segments);
}
$configPath = buildPath('config', 'database.php');
$uploadPath = buildPath('uploads', date('Y'), date('m'), 'file.jpg');
// Normalize path separators
function normalizePath($path) {
return str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path);
}
?>
File System Utilities
Copying and Moving Files
<?php
// Copy file
if (copy('source.txt', 'destination.txt')) {
echo "File copied successfully\n";
}
// Move/rename file
if (rename('old_name.txt', 'new_name.txt')) {
echo "File renamed successfully\n";
}
// Move file to different directory
rename('file.txt', 'backup/file.txt');
// Copy directory recursively
function copyDirectory($src, $dst) {
$dir = opendir($src);
mkdir($dst, 0755, true);
while (($file = readdir($dir)) !== false) {
if ($file != '.' && $file != '..') {
$srcPath = $src . DIRECTORY_SEPARATOR . $file;
$dstPath = $dst . DIRECTORY_SEPARATOR . $file;
if (is_dir($srcPath)) {
copyDirectory($srcPath, $dstPath);
} else {
copy($srcPath, $dstPath);
}
}
}
closedir($dir);
}
?>
File Permissions and Ownership
<?php
$filename = 'document.txt';
// Change file permissions
chmod($filename, 0644); // Owner: read/write, Group/Others: read
// Change file ownership (requires appropriate permissions)
chown($filename, 'www-data');
chgrp($filename, 'www-data');
// Get file owner information
$owner = fileowner($filename);
$group = filegroup($filename);
$ownerInfo = posix_getpwuid($owner);
$groupInfo = posix_getgrgid($group);
echo "Owner: " . $ownerInfo['name'] . "\n";
echo "Group: " . $groupInfo['name'] . "\n";
?>
Temporary Files
<?php
// Create temporary file
$tempFile = tempnam(sys_get_temp_dir(), 'myapp_');
file_put_contents($tempFile, 'Temporary data');
// Use temporary file
echo "Temp file: " . $tempFile . "\n";
echo "Content: " . file_get_contents($tempFile) . "\n";
// Clean up
unlink($tempFile);
// Create temporary directory
$tempDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'myapp_' . uniqid();
mkdir($tempDir, 0755);
// Use temporary directory
echo "Temp directory: " . $tempDir . "\n";
// Clean up (after use)
rmdir($tempDir);
?>
File Locking
<?php
// Exclusive file locking
$filename = 'counter.txt';
$handle = fopen($filename, 'c+');
if (flock($handle, LOCK_EX)) {
// Read current value
$count = (int)fread($handle, filesize($filename) ?: 1);
// Increment and write back
$count++;
ftruncate($handle, 0);
fseek($handle, 0);
fwrite($handle, $count);
// Release lock
flock($handle, LOCK_UN);
}
fclose($handle);
// Non-blocking lock
if (flock($handle, LOCK_EX | LOCK_NB)) {
// Got lock immediately
flock($handle, LOCK_UN);
} else {
echo "Could not acquire lock\n";
}
?>
Stream Operations
<?php
// Stream contexts for HTTP requests
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => json_encode(['key' => 'value'])
]
]);
$response = file_get_contents('https://api.example.com/data', false, $context);
// Filter streams
$input = "Hello World 123!";
$filtered = stream_filter_var($input, FILTER_SANITIZE_STRING);
// Custom stream filter
class UppercaseFilter extends php_user_filter {
public function filter($in, $out, &$consumed, $closing) {
while ($bucket = stream_bucket_make_writeable($in)) {
$bucket->data = strtoupper($bucket->data);
$consumed += $bucket->datalen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
}
stream_filter_register('uppercase', 'UppercaseFilter');
$handle = fopen('data.txt', 'r');
stream_filter_append($handle, 'uppercase');
echo stream_get_contents($handle);
fclose($handle);
?>
File System Monitoring
<?php
// Check disk space
$bytes = disk_free_space('/');
echo "Free space: " . formatBytes($bytes) . "\n";
$total = disk_total_space('/');
echo "Total space: " . formatBytes($total) . "\n";
function formatBytes($size, $precision = 2) {
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
for ($i = 0; $size > 1024 && $i < count($units) - 1; $i++) {
$size /= 1024;
}
return round($size, $precision) . ' ' . $units[$i];
}
// File system statistics
$stats = stat('document.txt');
echo "Device: " . $stats['dev'] . "\n";
echo "Inode: " . $stats['ino'] . "\n";
echo "Size: " . $stats['size'] . "\n";
echo "Access time: " . date('Y-m-d H:i:s', $stats['atime']) . "\n";
echo "Modify time: " . date('Y-m-d H:i:s', $stats['mtime']) . "\n";
echo "Change time: " . date('Y-m-d H:i:s', $stats['ctime']) . "\n";
?>
Error Handling
<?php
// Handle file operation errors
function safeFileRead($filename) {
if (!file_exists($filename)) {
throw new InvalidArgumentException("File does not exist: {$filename}");
}
if (!is_readable($filename)) {
throw new RuntimeException("File is not readable: {$filename}");
}
$content = file_get_contents($filename);
if ($content === false) {
throw new RuntimeException("Failed to read file: {$filename}");
}
return $content;
}
try {
$content = safeFileRead('config.txt');
echo $content;
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
// Check for errors with file operations
function safeCreateDirectory($path, $permissions = 0755) {
if (!mkdir($path, $permissions, true) && !is_dir($path)) {
$error = error_get_last();
throw new RuntimeException("Failed to create directory: " . $error['message']);
}
return true;
}
?>
Best Practices
File Handling Security
<?php
// Validate file paths to prevent directory traversal
function validatePath($path, $allowedDir) {
$realPath = realpath($allowedDir . DIRECTORY_SEPARATOR . $path);
$allowedPath = realpath($allowedDir);
return $realPath && str_starts_with($realPath, $allowedPath);
}
// Safe file upload handling
function handleFileUpload($uploadedFile, $uploadDir) {
// Validate file
if (!isset($uploadedFile['tmp_name']) || !is_uploaded_file($uploadedFile['tmp_name'])) {
throw new InvalidArgumentException('Invalid uploaded file');
}
// Sanitize filename
$filename = basename($uploadedFile['name']);
$filename = preg_replace('/[^a-zA-Z0-9._-]/', '', $filename);
// Validate path
if (!validatePath($filename, $uploadDir)) {
throw new InvalidArgumentException('Invalid file path');
}
$destination = $uploadDir . DIRECTORY_SEPARATOR . $filename;
if (!move_uploaded_file($uploadedFile['tmp_name'], $destination)) {
throw new RuntimeException('Failed to move uploaded file');
}
return $destination;
}
?>
Performance Considerations
<?php
// Use appropriate functions for file size
function getFileSize($filename) {
// For large files, use file handles
if (($handle = fopen($filename, 'r')) !== false) {
fseek($handle, 0, SEEK_END);
$size = ftell($handle);
fclose($handle);
return $size;
}
return filesize($filename);
}
// Efficient file processing for large files
function processLargeFile($filename, $callback) {
$handle = fopen($filename, 'r');
if (!$handle) {
throw new RuntimeException("Cannot open file: {$filename}");
}
while (($line = fgets($handle)) !== false) {
$callback(trim($line));
}
fclose($handle);
}
// Memory-efficient file copying
function copyLargeFile($source, $destination, $bufferSize = 8192) {
$src = fopen($source, 'rb');
$dest = fopen($destination, 'wb');
if (!$src || !$dest) {
throw new RuntimeException('Failed to open files for copying');
}
while (!feof($src)) {
$buffer = fread($src, $bufferSize);
fwrite($dest, $buffer);
}
fclose($src);
fclose($dest);
}
?>
PHP's filesystem functions provide powerful tools for file and directory operations while maintaining security and performance considerations.