PHP, being a server-side language, offers convenient access to the filesystem. In this blog post, we will explore some basic operations on files and folders using PHP.
Checking if a File Exists
To check if a file exists, we can use the file_exists()
function like this:
file_exists('test.txt'); // true
Getting the Size of a File
To get the size of a file, we can use the filesize()
function:
filesize('test.txt');
Opening a File
To open a file, we can use the fopen()
function. In the following example, we open the file test.txt
in read-only mode and store the file descriptor in the variable $file
:
$file = fopen('test.txt', 'r');
Remember to close the file after you are done using it by calling fclose($fd)
.
Reading the Content of a File
To read the content of a file into a variable, we can use fread()
or fgets()
. Here are two examples:
$file = fopen('test.txt', 'r');
$content = fread($file, filesize('test.txt'));
$file = fopen('test.txt', 'r');
$content = '';
while (!feof($file)) {
$content .= fgets($file, 5000);
}
The feof()
function is used to check if we have reached the end of the file, and fgets()
reads 5000 bytes at a time.
Reading a File Line by Line
If you want to read a file line by line, you can use the fgets()
function in a loop:
$file = fopen('test.txt', 'r');
while(!feof($file)) {
$line = fgets($file);
// do something with the line
}
Writing to a File
To write to a file, you need to open it in write mode and then use the fwrite()
function:
$data = 'test';
$file = fopen('test.txt', 'w');
fwrite($file, $data);
fclose($file);
Deleting a File
To delete a file, you can simply use the unlink()
function:
unlink('test.txt');
These are the basics of working with files and folders in PHP. Of course, there are many more functions available in the PHP filesystem documentation for more advanced operations.