In this article Directory Management Function in PHP we give the information about There are many built-in functions available in PHP to easily manage files and directories. These functions are helpful in handling the creation, reading, writing, renaming, deletion etc. of files and directories.
File and Directory Management Function in PHP
There are many built-in functions available in PHP to easily manage files and directories. These functions are helpful in handling the creation, reading, writing, renaming, deletion etc. of files and directories.
Functions for working with different types of files and directories will be discussed in this article.
-
File Manipulation Functions
1.1 Creating a File
$file = fopen(“example.txt”, “w”); // create new file
fclose($file);
fopen(“file_name”, “w”) : Open the file in ‘write’ mode.
w : Overwrites the file, if the file already exists.
1.2 Reading a File
$file = fopen(“example.txt”, “r”); //open the file for reading
$content = fread($file, filename(“example.txt”));
fclose($file);
echo $content;
fread($file, filename(“file_name”)) : Reading the file.
1.3 Writing to a File
$file = fopen(“example.txt”, “a”); // Open the file in ‘append’ mode
fwrite($file, “New Data”); // write new data
fclose($file);
fwrite($file, “data”) : Write data to the file.
a :To append to the file.
1.4 Deleting a File
unlink(“example.txt”); //deleting the file
1.5 Renaming a File
rename(“old_name.txt”, “new_name.txt”); // changing file name
- Directory Manipulation Functions
2.1 Creating a Directory
mkdir(“new_directory”); // create new directory
2.2 Reading a Directory
$dir = opendir(“existing_directory”);
while (($file = readdir($dir)) !== false) {
echo $file . “<br>”; // show files in directory
}
closeddir($dir);
opendir(“directory_name”) :Open the directory.
readdir($dir) :Listing the files present in the directory.
closedir($dir) :To close the directory.
2.3 Removing a Directory
rmdir(“directory_name”); //deleting the directory
2.4 Copying a File to Another Directory
copy(“source_file.txt”, “destination_directory/destination_file.txt”);
2.5 Changing Directory Permissions
chmod(“example.txt”, 0777); // changing file/directory permissions
Conclusion
- Various types of operations like reading, writing, deleting, renaming, etc. can be easily performed with files and directories in PHP.
- Using these functions users can manage files and directories as per their requirement.
Some More:
POP- Introduction to Programming Using ‘C’
OOP – Object Oriented Programming
DBMS – Database Management System
RDBMS – Relational Database Management System
Join Now: Data Warehousing and Data Mining