Initial Introduction to the File System in PHP
One of the attractive capabilities of the PHP language is its ability to work with the file system. The file system allows us to easily control files and folders on the server. We can create, read, write, and delete files, or obtain more information about them.
PHP provides several functions for managing the file system that make working with files very simple and convenient. By using these functions, you can build applications that require interaction with the file system, such as content management websites, image galleries, and even databases based on files.
Creating and Writing to Files
To create a file and write to it, you can use the fopen
function along with the write mode 'w' or 'w+'. The 'w' mode will create the file if it does not exist, and if it does exist, it will truncate its content.
<?php
$filename = 'example.txt';
$file = fopen($filename, 'w');
if ($file) {
fwrite($file, "This is a sample file.");
fclose($file);
} else {
echo "Cannot open the file.";
}
?>
Reading from Files
To access the contents of a file and read it, you can use the fread
function. This function allows us to read up to a specified size of bytes.
<?php
$file = fopen($filename, 'r');
if ($file) {
$filesize = filesize($filename);
$content = fread($file, $filesize);
fclose($file);
echo $content;
} else {
echo "Cannot open the file for reading.";
}
?>
Explanation Line by Line
$filename = 'example.txt';
We create a variable for the file name.
$file = fopen($filename, 'w');
We open the file in write mode.
fwrite($file, "This is a sample file.");
We write some data into the file.
fclose($file);
We close the file to save changes.
filesize($filename);
We obtain the size of the file for reading.
$content = fread($file, $filesize);
We read the content of the file and store it in a variable.