php_ref_filesystem
PHP Filesystem Functions
Section titled “PHP Filesystem Functions”PHP Filesystem Introduction
Section titled “PHP Filesystem Introduction”PHP provides a comprehensive set of functions for interacting with the server’s filesystem. These allow you to read, write, create, delete, and manage files and directories.
Security Note: Filesystem operations can have significant security implications. Always validate and sanitize user-provided paths or filenames to prevent directory traversal attacks (e.g., accessing files outside the intended directories like ../../etc/passwd). Ensure appropriate file and directory permissions are set on your server.
Installation
Section titled “Installation”Filesystem functions are part of the PHP core. No installation is needed.
Path Separators (Unix / Windows Compatibility)
Section titled “Path Separators (Unix / Windows Compatibility)”PHP provides the DIRECTORY_SEPARATOR constant, which automatically uses the correct separator (/ for Unix-like systems, \ for Windows). It’s best practice to use this constant when constructing paths to ensure cross-platform compatibility.
<?php// Good practice for cross-platform paths$filePath = 'data' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'logo.png';
// PHP often handles forward slashes '/' correctly even on Windows$filePathSimple = 'data/images/logo.png';// Using '/' is generally safe and often preferred for simplicity?>When working with user input or paths from different sources, consider using functions like realpath() to normalize and resolve paths.
Common Filesystem Functions
Section titled “Common Filesystem Functions”Here are some frequently used filesystem functions:
| Function / Category | Description |
|---|---|
| Reading Files | |
| file_get_contents() | Reads entire file into a string (convenient for smaller files). |
| fopen() | Opens a file or URL, returning a file pointer resource. |
| fread() | Reads a specified number of bytes from an open file pointer. |
| fgets() | Reads a line from an open file pointer. |
| fgetcsv() | Parses a line from an open file pointer for CSV fields. |
| file() | Reads entire file into an array of lines. |
| readfile() | Reads a file and writes it directly to the output buffer. |
| Writing Files | |
| file_put_contents() | Writes data (string or array) to a file (convenient for simple writes, can create/overwrite). |
| fwrite() / fputs() | Writes to an open file pointer. |
| fputcsv() | Formats a line as CSV and writes it to an open file pointer. |
| File/Directory Checks | |
| file_exists() | Checks whether a file or directory exists. |
| is_file() | Checks if the path is a regular file. |
| is_dir() | Checks if the path is a directory. |
| is_readable() | Checks if a file/directory exists and is readable. |
| is_writable() / is_writeable() | Checks if a file/directory exists and is writable. |
| is_executable() | Checks if the path is executable. |
| File/Directory Manipulation | |
| copy() | Copies a file. |
| rename() | Renames or moves a file or directory. |
| unlink() | Deletes a file. |
| mkdir() | Creates a directory. |
| rmdir() | Removes an empty directory. |
| touch() | Sets access and modification time of a file (creates if it doesn’t exist). |
| chmod() | Changes file mode (permissions). |
| chown() | Changes file owner. |
| chgrp() | Changes file group. |
| File Information | |
| filesize() | Gets file size in bytes. |
| filetype() | Gets file type (e.g., file, dir, link). |
| filemtime() | Gets file modification time (Unix timestamp). |
| fileatime() | Gets file last access time (Unix timestamp). |
| filectime() | Gets file inode change time (Unix timestamp). |
| stat() / fstat() | Gives detailed information about a file/open file pointer. |
| pathinfo() | Returns information about a file path (directory, basename, extension, filename). |
| basename() | Returns trailing name component of path. |
| dirname() | Returns parent directory’s path. |
| realpath() | Returns canonicalized absolute pathname. |
| Directory Operations | |
| scandir() | Lists files and directories inside the specified path into an array. |
| opendir() / readdir() / closedir() | Procedural way to read directory entries one by one. |
| glob() | Finds pathnames matching a pattern (e.g., *.txt). |
| File Pointers | |
| fclose() | Closes an open file pointer. |
| feof() | Tests for end-of-file on a file pointer. |
| fseek() | Seeks on a file pointer. |
| ftell() | Returns the current position of the file read/write pointer. |
| rewind() | Rewinds the position of a file pointer. |
Note: fgetss() was deprecated in PHP 7.3 and removed in PHP 8.0. Do not use it.
Object-Oriented Alternatives
Section titled “Object-Oriented Alternatives”PHP also provides object-oriented interfaces for filesystem interaction through the Standard PHP Library (SPL):
SplFileInfo: Provides a high-level object-oriented interface for information about a specific file or directory.DirectoryIterator: An iterator to easily loop through the contents of a directory, yieldingSplFileInfoobjects.RecursiveDirectoryIterator/RecursiveIteratorIterator: For traversing nested directories.
Example using DirectoryIterator:
<?php$path = './my_directory'; // Ensure this directory exists
try { $iterator = new DirectoryIterator($path); foreach ($iterator as $fileInfo) { if ($fileInfo->isFile()) { echo $fileInfo->getFilename() . " - Size: " . $fileInfo->getSize() . " bytes\n"; } elseif ($fileInfo->isDir() && !$fileInfo->isDot()) { // Exclude '.' and '..' echo $fileInfo->getFilename() . " [Directory]\n"; } }} catch (Exception $e) { echo "Error accessing directory: " . $e->getMessage();}?>Stream Wrappers
Section titled “Stream Wrappers”Many filesystem functions can work with more than just local files. PHP’s stream wrapper system allows treating various resources like files. Common examples include:
file://: Accessing the local filesystem (usually the default).http://,https://: Accessing URLs via HTTP(S). Requiresallow_url_fopen=Oninphp.ini.ftp://,ftps://: Accessing resources via FTP(S). Requiresallow_url_fopen=On.php://: Accessing various I/O streams (e.g.,php://stdin,php://stdout,php://stderr,php://input,php://output,php://memory,php://temp).
Example reading request body:
<?php// Get raw POST data$requestBody = file_get_contents('php://input');
// Note: 'php://input' is not available with enctype="multipart/form-data"?>Caution: Enabling allow_url_fopen can have security risks if user input is directly used in functions like file_get_contents() or include without proper validation, potentially leading to Remote File Inclusion (RFI) vulnerabilities. Consider using cURL for more robust and secure handling of remote HTTP requests.