Everything You Need To Know About PHP File System
Posted by TotalDCThis time we will learn how to create, access and manipulate files dynamically with PHP file system functions.
Working With PHP File System
As you know PHP is A server-side programming language, that allows you to work with files stored on the web server. In this tutorial, you will learn how to create, access, and manipulate files on your web server using the PHP file system functions.
How To Open A File With PHP FOPEN() Function
To work with a file you need to open it first. The fopen() function is used to do just that – open the file. The basic syntax of this function looks like this:
fopen(filename, mode)
The first parameter passed to fopen() specifies the name of the file that you want to open. The second parameter specifies in what mode the file will be opened. For example:
<?php
$test= fopen("data.txt", "r");
?>
Here are the modes that the file can be opened:
Modes | What it does |
r | Open the file for reading only. |
r+ | Open the file for reading and writing. |
w | Open the file for reading and writing and clear the contents of file. If the file does not exist, PHP will attempt to create it. |
w+ | Open the file for writing only. Return false and generate an error if the file already exists. If the file does not exist, PHP will attempt to create it. |
a | Append. Opens the file for writing only. Preserves file content by writing to the end of the file. If the file does not exist, PHP will attempt to create it. |
a+ | Read/Append. Opens the file for reading and writing. Preserves file content by writing to the end of the file. If the file does not exist, PHP will attempt to create it. |
x | Open the file for reading and writing; otherwise, it has the same behavior as ‘x’. |
x+ | Open the file for reading and writing; otherwise it has the same behavior as ‘x’. |
You should always implement a simple check whether a file or directory exists or not before trying to access it, with the PHP file_exists() function. And if you try to open the file that does not exist, you will get a PHP error message.
<?php
$file = "data.txt";
// Check if file exists
if(file_exists($file)){
// Open the file
$handle = fopen($file, "r");
} else{
print "ERROR: File does not exist.";
}
?>
How To Close A File With FCLOSE() Function In PHP
When you are done working with the file, it needs to be closed. To do that you need to use fclose() function. Here is an example:
<?php
$file = "data.txt";
// Check if file exist
if(file_exists($file)){
// Open the file
$test= fopen($file, "r") or die("ERROR: Cannot open the file.");
/* Some code to be executed */
// Closing the file
fclose($test);
} else{
print "ERROR: File does not exist.";
}
?>
How To Read Files With FREAD() Function in PHP
PHP has several functions for reading data from a file. You can read just one character or an entire file with a single function.
How To Read Fixed Number Of Characters In PHP
The fread() function can be used to read a specified number of characters from a file. The basic syntax of this function looks like this:
fread(file handle, length in bytes);
This function takes two parameters. The file handle and the number of symbols to read. The following example shows how to read 20 symbols (including spaces) from the “data.txt” file:
<?php
$file = "data.txt";
// Check if file exists
if(file_exists($file)){
// Open the file for reading
$test= fopen($file, "r") or die("ERROR: Cannot open the file.");
// Read fixed number of symbols from the file
$content = fread($test, "20");
// Closing the file
fclose($test);
// Display the result
print $content;
} else{
print "ERROR: File does not exist.";
}
?>
This example will produce the following output:
The quick brown fox
Reading The Entire File With PHP
The fread() function can be used in conjugation with the filesize() function to read the entire file at once. The filesize() function returns the size of the file.
<?php
$file = "data.txt";
// Check if file exist
if(file_exists($file)){
// Open the file for reading
$test = fopen($file, "r") or die("ERROR: Cannot open the file.");
// Reading the entire file
$content = fread($test, filesize($file));
// Closing the file handle
fclose($test);
// Display the result
print $content;
} else{
print "ERROR: File does not exist.";
}
?>
This example will produce the following output:
The quick brown fox jumps over the lazy dog.
The easiest way to read the entire contents of a file in PHP is with the readfile() function. This function allows you to read the contents of a file without opening it. The following example will generate the same output as the previous example:
<?php
$file = "data.txt";
// Check if file exist
if(file_exists($file)){
// Reads and outputs the entire file
readfile($file) or die("ERROR: Cannot open the file.");
} else{
print "ERROR: File does not exist.";
}
?>
Result:
The quick brown fox jumps over the lazy dog.
Another way to read the whole file without opening it is to use file_get_contents() function. This function accepts the name and path of a file and returns a string. Here is an example:
<?php
$file = "data.txt";
// Check if file exist
if(file_exists($file)){
// Reading the entire file
$content = file_get_contents($file) or die("ERROR: Cannot open the file.");
// Display the result
print $content;
} else{
print "ERROR: File does not exist.";
}
?>
The third method of reading an entire file is to use file() function. It is similar to file_get_contents() function but it returns an array rather than a string. To process the file data, you need to iterate the array using a foreach() loop. Here’s an example:
<?php
$file = "data.txt";
// Check if file exist
if(file_exists($file)){
// Reading the entire file into an array
$arr = file($file) or die("ERROR: Cannot open the file.");
foreach($arr as $line){
print $line;
}
} else{
print "ERROR: File does not exist.";
}
?>
How To Write Data Into Files Using PHP FWRITE() Function
You can write data to a file using the PHP fwrite() function. The basic syntax of this function looks like this:
fwrite(file handle, string)
The fwrite() function takes two parameters. A file name and the string that needs to be written that file. Let’s look at the example:
<?php
$file = "note.txt";
// Your string
$data = "The quick brown fox jumps over the lazy dog.";
// Open the file
$test= fopen($file, "w") or die("ERROR: Cannot open the file.");
// Write data to the file
fwrite($test, $data) or die ("ERROR: Cannot write the file.");
// Close the file
fclose($test);
print "Data written to the file successfully.";
?>
If the “note.txt” file doesn’t exist PHP will automatically create it and write the data. And if it exists content of the file will be erased and populated with new data. If you don’t want to overwrite existing data you can use mode a instead of w.
Another way to write into the file is using file_put_contents() function. It’s an easy method of writing data to the file without even opening it.
<?php
$file = "note.txt";
// Your string
$data = "The quick brown fox jumps over the lazy dog.";
// Write data to the file
file_put_contents($file, $data) or die("ERROR: Cannot write the file.");
print "Data written to the file successfully.";
?>
If the file already exists it will be overwritten. If you don’t want to overwrite existing data you can pass the FILE_APPEND flag as the third parameter to the file_put_contents() function.
<?php
$file = "note.txt";
// Your string
$data = "The quick brown fox jumps over the lazy dog.";
// Write data to the file
file_put_contents($file, $data, FILE_APPEND) or die("ERROR: Cannot write the file.");
print "Data written to the file successfully.";
?>
How To Rename File Using RENAME() Function In PHP
You can rename a file or directory using the rename() function:
<?php
$file = "file.txt";
// Check if file exists
if(file_exists($file)){
// Attempt to rename the file
if(rename($file, "newfile.txt")){
print "File renamed successfully.";
} else{
print "ERROR: File cannot be renamed.";
}
} else{
print "ERROR: File does not exist.";
}
?>
How To Remove File With UNLINK() Function In PHP
You can delete files or directories using the PHP’s unlink() function:
<?php
$file = "note.txt";
// Check if file exists
if(file_exists($file)){
// Attempt to delete the file
if(unlink($file)){
print "File removed successfully.";
} else{
print "ERROR: File cannot be removed.";
}
} else{
print "ERROR: File does not exist.";
}
?>
PHP Filesystem Functions
This table provides an overview of some other useful PHP filesystem functions that can be used for reading and writing the files dynamically.
Function | Description |
fgetc() | Reads a single character at a time. |
fgets() | Reads a single line at a time. |
fgetcsv() | Reads a line of comma-separated values. |
filetype() | Returns the type of the file. |
feof() | Check whether the file is a regular file. |
is_file() | Check whether the file is a directory. |
is_dir() | Check whether the file is executable. |
is_executable() | Checks whether the file is executable. |
realpath() | Returns canonicalized absolute pathname. |
rmdir() | Removes an empty directory. |