File Handling in php
Section 5: File Handling in PHP
File handling in PHP allows you to perform operations like opening, reading, and writing to text files. Additionally, you can work with directories by creating, deleting, and listing them. Let's explore these concepts with detailed coding examples.
Reading and Writing to Files
Opening and Reading from a Text File
<?php
// File path
$file_path = "example.txt";
// Open the file for reading
$file_handle = fopen($file_path, "r");
// Check if the file is opened successfully
if ($file_handle) {
// Read the file line by line
while (!feof($file_handle)) {
$line = fgets($file_handle);
echo $line;
}
// Close the file
fclose($file_handle);
} else {
echo "Unable to open the file.";
}
?>
Writing to a Text File
<?php
// File path
$file_path = "example.txt";
// Open the file for writing
$file_handle = fopen($file_path, "w");
// Check if the file is opened successfully
if ($file_handle) {
// Write content to the file
fwrite($file_handle, "Hello, PHP!");
// Close the file
fclose($file_handle);
echo "Content written to the file.";
} else {
echo "Unable to open the file.";
}
?>
Working with Directories
Creating a Directory
<?php
// Directory name
$dir_name = "new_directory";
// Check if the directory does not exist
if (!is_dir($dir_name)) {
// Create the directory
mkdir($dir_name);
echo "Directory created successfully.";
} else {
echo "Directory already exists.";
}
?>
Deleting a Directory
<?php
// Directory name
$dir_name = "directory_to_delete";
// Check if the directory exists
if (is_dir($dir_name)) {
// Remove the directory
rmdir($dir_name);
echo "Directory deleted successfully.";
} else {
echo "Directory does not exist.";
}
?>
Listing Files in a Directory
<?php
// Directory path
$dir_path = "example_directory";
// Check if the directory exists
if (is_dir($dir_path)) {
// Open the directory
$dir_handle = opendir($dir_path);
// Read and display the files in the directory
while (($file = readdir($dir_handle)) !== false) {
echo $file . "<br>";
}
// Close the directory
closedir($dir_handle);
} else {
echo "Directory does not exist.";
}
?>
These examples illustrate various file handling operations in PHP, including reading and writing to text files, creating and deleting directories, and listing files in a directory.