Advanced PHP File and Directory Operations
This article provides a comprehensive guide to advanced PHP file and directory handling, covering reading and writing files, retrieving file metadata, manipulating file pointers, traversing and managing directories, handling uploads, error handling, and best practices with clear code examples.
In PHP development, mastering file and directory operations is essential for tasks such as handling uploads, logging, and configuration management. This guide explores advanced techniques to improve development efficiency.
1. File Operations
1.1 File Read/Write
fopen(): Open a file and return a file pointer resource.
fread(): Read file contents.
fwrite(): Write data to a file.
fclose(): Close the file pointer.
file_get_contents(): Read the entire file into a string.
file_put_contents(): Write a string to a file.
Example:
// Read file content
$file = fopen("example.txt", "r");
$content = fread($file, filesize("example.txt"));
fclose($file);
// Write content to file
$file = fopen("example.txt", "w");
fwrite($file, "Hello, World!");
fclose($file);1.2 File Information Retrieval
filesize(): Get file size.
filemtime(): Get last modification time.
file_exists(): Check if a file exists.
is_file(): Determine if the path is a file.
is_readable(): Check if the file is readable.
is_writable(): Check if the file is writable.
Example:
if (file_exists("example.txt")) {
echo "File size: " . filesize("example.txt") . " bytes";
echo "Last modified: " . date("Y-m-d H:i:s", filemtime("example.txt"));
}1.3 File Pointer Operations
fseek(): Move the file pointer to a specific position.
ftell(): Return the current position of the file pointer.
rewind(): Move the file pointer to the beginning of the file.
Example:
$file = fopen("example.txt", "r");
fseek($file, 10); // Move pointer to the 10th byte
echo fread($file, 5); // Read 5 bytes
fclose($file);2. Directory Operations
2.1 Directory Traversal
scandir(): List files and directories inside a directory.
glob(): Find pathnames matching a pattern.
Example:
// List all files in the current directory
$files = scandir(".");
foreach ($files as $file) {
echo $file . "\n";
}
// Find all .txt files
$txtFiles = glob("*.txt");
foreach ($txtFiles as $file) {
echo $file . "\n";
}2.2 Directory Creation and Deletion
mkdir(): Create a directory.
rmdir(): Remove an empty directory.
Example:
// Create a directory
mkdir("new_directory");
// Delete a directory
rmdir("new_directory");2.3 Directory Information Retrieval
is_dir(): Determine if the path is a directory.
opendir(): Open a directory handle.
readdir(): Read entries from the directory.
closedir(): Close the directory handle.
Example:
$dir = opendir(".");
while (($file = readdir($dir)) !== false) {
echo $file . "\n";
}
closedir($dir);3. File Upload
$_FILES: Superglobal containing uploaded file information.
move_uploaded_file(): Move an uploaded file to a new location.
Example:
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file"]["tmp_name"];
$name = basename($_FILES["file"]["name"]);
move_uploaded_file($tmp_name, "uploads/$name");
}4. Error Handling
error_reporting(): Set the level of error reporting.
ini_set(): Set configuration options.
try...catch: Catch exceptions.
Example:
try {
$file = fopen("nonexistent.txt", "r");
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}5. Best Practices
Prefer absolute paths over relative paths.
Check file existence and read/write permissions.
Use exception handling to capture errors.
Close file pointers and directory handles promptly.
Validate uploaded files for security.
Mastering PHP file and directory operations is a fundamental skill for advanced PHP development. By following the techniques and best practices presented, you can write secure, efficient, and maintainable code tailored to your project's needs.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.