Have you ever tried to manage files and folders using PHP? The programming language offers various features to manipulate the filesystem. Finding its roots back in the C programming language, the method to open-, read- and write to files are the same as for the old [but popular] language.
Table of contents
- The PHP filesystem API
- How to read a file with PHP?
- How to read CSV data?
- How to write to a file with PHP?
- How to write CSV data to a file?
- How to delete a file with PHP?
The PHP filesystem API
Let’s start with a quick reference listing the important functions of the PHP filesystem API that you need to know about if you want to manage files and folders with PHP:
fopen()
/fsockopen()
/popen()
: Respectively opens a file, a UNIX domain socket connection and a process file pointer.fread()
/fgets()
/fgetss()
: Read a file, get one line from a file pointer and get one line with stripped HTML tags.fwrite()
/fputs()
: Binary-safe file write. These functions write the contents to a file stream resource.fseek()
/ftell()
/feof()
: Move the cursor in a file stream resource, tell the current cursor position and tell whether the end of the file is reached (uses the\0
byte).file_get_contents()
/file_put_contents()
: Reads an entire file content into astring
variable, or write the full file contents.fgetcsv()
/fputcsv()
: Get one line from a file stream resource and parse CSV fields (comma-separated values), or write one line in a file stream resource formatting the line as CSV.file()
/readfile()
: Read an entire file in an array (of lines), or read a file and write it ti the output buffer.
All the listed method can be freely used within WordPress installations as well, make sure to have a read here if you are looking for information about changing WordPress files.
How to read a file with PHP?
There are many ways to achieve this with PHP. First is using the standard fopen
, fread
and fclose
methods. The first method that we will inspect to read the content of a file, is using fopen()
and the binary-safe fread()
function.
<?php
// Opens a file stream
$file_name = "/tmp/my-file.txt";
$stream = fopen($file_name, "r");
// Read the entire file
$contents = fread($stream, filesize($file_name));
// Closes the file stream
fclose($stream);
?>
You could also be limited on the memory-side, which would require that you read chunks of data, rather than the entire file all at once. This methodology is more scalable and applies well to bigger files.
<?php
// Opens a file stream
$file_name = "/tmp/my-file.txt";
$stream = fopen($file_name, "r");
$chunk_size = 1024; // we read 1024 bytes
$chunks = [];
while (!feof($stream)) {
$chunk_1024 = fread($stream, 1024);
array_push($chunks, $chunk_1024);
}
// Closes the file stream
fclose($stream);
?>
How to read CSV data?
Next, PHP also features the comma-separated values (CSV) format when reading contents of a file. The fgetcsv()
function can spare you the boilerplate source code of parsing comma-separated columns.
<?php
// Opens a file stream
$file_name = "/tmp/my-file.txt";
$stream = fopen($file_name, "r");
$rows = [];
while(($data = fgetcsv($stream, 1024, ",")) !== false) {
array_push($rows, $data);
}
// Closes the file stream
fclose($stream);
?>
How to write to a file with PHP?
We continue now by having a look at the file writing API in how to manage files and folders with PHP. Writing to a file with PHP is relatively simple and there are also many ways to do it. In this section, we’ll first focus on the basic API with the fwrite()
function.
<?php
// Opens a file stream
$file_name = "/tmp/my-file.txt";
$stream = fopen($file_name, "a+");
$content = "My file content";
fwrite($stream, $content);
// Closes the file stream
fclose($stream);
?>
Next, let’s write at a specific position in the file. Using the fseek() function to move the cursor inside the stream, it is possible to skip the contents of a file until a known cursor position. This is notably useful with files that contain pre-defined headers or footers.
<?php
// Opens a file stream
$file_name = "/tmp/my-file.txt";
$stream = fopen($file_name, "w");
$content = "My file content";
fseek($stream, 1024); // move 1024 bytes in the file
fwrite($stream, $content);
// Closes the file stream
fclose($stream);
?>
How to write CSV data to a file?
We continue with PHP featuring the comma-separated values (CSV) format when writing contents of a file. The fputcsv()
function can spare you the boilerplate source code of formatting comma-separated rows of data.
<?php
// Opens a file stream
$file_name = "/tmp/my-file.txt";
$stream = fopen($file_name, "w");
$data = [
["id" => 123, "name" => "Free Code Sources"],
["id" => 124, "name" => "Free Guides"],
["id" => 125, "name" => "Free Tutorials"],
];
// writing row by row
foreach ($data as $data_row) {
fputcsv($stream, $data_row);
}
// Closes the file stream
fclose($stream);
?>
How to delete a file with PHP?
This feature is not part of the functions listed above and is highly dependent on the underlying operating system. There are a couple of ways you can achieve the removal of files using the PHP programming language, but you must make sure that they are used with the correct operating system.
Delete a file using the unlink() function
First, the unlink()
function is available on all UNIX-like operating systems, including Linux, FreeBSD and Mac OS. This function deletes a file and takes a filename
parameter of type string
.
<?php
unlink("/tmp/my-file.txt");
?>
Delete a folder using the rmdir() function
You can also use the rmdir()
function to delete folders. This method also works for Windows operating systems. Note that the directory must be empty for the operation to succeed, and permissions must be satisfied.
<?php
unlink("/tmp/my-folder");
?>
Delete files and folders using the exec() function
Another method to remove files and folders from the filesystem, is to use the exec()
function which executes external programs. This method is compatible with all the major operating systems.
<?php
// Command and flags differ from UNIX to Windows
$cmd = PHP_OS === "Windows" ? "rd" : "rm";
$flags = PHP_OS === "Windows" ? "/s /q" : "-f";
// Escaping parameters works for all OSs
$params = escapeshellarg("/tmp/my-file.txt");
// Constructs the command prompt
$prompt = `$cmd $flags $parameters`;
exec($prompt);
?>