In this article Working with files in PHP we give the information about Using PHP we can read, write, modify files and store them in a directory. Also we will learn how to handle file and directory related activities in PHP.
-
Working with Files in PHP
Creating a File
<?php
$file = fopen(“example.txt”, “w”);
if ($file) {
fwrite($file, “This is a new text file.”);
fclose($file);
echo “The file has been created successfully.”;
} else {
echo “There was an error creating file!”;
}
?>
- The file is opened using fopen().
- The file can be written using w mode (Write mode).
- Text is added to the file using fwrite().
- The file is closed with fclose().
Reading from a File
<?php
$file = fopen(“example.txt”, “r”);
if ($file) {
$content = fread($file, filename(“example.txt”));
fclose($file);
echo $content;
} else {
echo “There was an error reading file!”;
}
?>
- Let’s open the file for reading using r mode.
- Let’s read the contents of the file using fread().
- The length of the file is obtained using filesize().
Appending to a File
<?php
$file = fopen(“example.txt”, “a”);
if ($file) {
fwrite($file, “\nThis is a new line.”);
fclose($file);
echo “New line added to file.”;
} else {
echo “There was an error adding file!”;
}
?>
Using a mode adds text to the end of the file.
Deleting a File
<?php
if (unlink(“example.txt”)) {
echo “The file has been successfully deleted.”;
} else {
echo “There was an error deleting file!”;
}
?>
The file is deleted using unlink().
-
Working with Directories in PHP
Creating a Directory
<?php
if (mkdir(“new_directory”)) {
echo “The directory has been created successfully.”;
} else {
echo “There was an error creating the directory!”;
}
?>
A new directory is created using mkdir().
Listing Files in a Directory
<?php
$dir = opendir(“new_directory”);
while (($file = readdir($dir)) !== false) {
echo $file . “<br>”;
}
closeddir($dir);
?>
}
?>
- Open a directory using opendir().
- Loop through all the files inside a directory through readdir().
- Close the directory with closedir().
Deleting a Directory
Deleted a directory using rmdir()
<?php
if (rmdir(“new_directory”)) {
echo “The directory has been successfully deleted.”;
} else {
echo “There was an error deleting the directory!”;
}
?>
File and Directory Permissions
File permissions are used to control files and directories in PHP. You can set the permissions of a file or directory using chmod().
chmod(“example.txt”, 0777); // set file permissions
Conclusion
- Files and directories can be easily read, written, modified and managed using PHP.
- Various functions are used for file operations like fopen(), fclose(), fwrite(), and for directory operations mkdir(), opendir(), rmdir().
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