PHP File System Functions

PHP is a server-side language that allows working with files, directories stored in the webserver. PHP file system allows us to create the file, read file character by character, read file line by line, write the file, append file, delete file, and close file.

PHP Open File – fopen()

In order to work with PHP file, you first need to open the file. The PHP fopen() function opens the file.

The basic syntax of fopen() is as below.

fopen(filename, mode)

HERE,

  • “fopen()” is the name of the function to open the file.
  • “filename” specifies the name of the filename which needs to be open.
  • “mode” specifies the mode in which the file needs to be open. For example- “r” for reading mode, “w” for write mode.

Now let’s check one basic example of fopen() to get clarity on the concept.

Example

<?php
      $handle = fopen("file.txt", "r");
?>

The file can be opened in any of the following modes.

Mode Description
r Open the file for reading only.
r+ Open the file for reading and writing.
w Open the file for writing only and clears the contents of the file. If the file does not exist, PHP will attempt to create it.
w+ Open the file for reading and writing and clears the contents of the file. 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 writing only. Return FALSE and generates an error if the file already exists. 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’.

PHP file_exists() function

The file_exists() function checks if the particular file exists or not in the specified path. Whenever you try to access a file which does not exist, PHP will give an error. So it is better to check the file’s existence before trying to access the file.

Syntax

<?php
      file_exists($filename);
?>

Here,

  • “file_exists()” is the name of the function which returns true if the file exists and returns false if the file does not exist.
  • “$filename” – filename along with the path to be checked.

Example

<?php
$file = "file.txt";
 
// Check the existence of file
if(file_exists($file)){
    // Attempt to open the file
    $handle = fopen($file, "r");
} else{
    echo "Error: File does not exist.";
}
?>

Output

Error: File does not exist.

PHP File Close – fclose() Function

Once you have completed your work with the file, you need to close the file in a proper way. The fclose() function is used to close the file in PHP.

Example

<?php
$file = "file.txt";
 
// Check the existence of file
if(file_exists($file)){
    // Open the file for reading
    $handle = fopen($file, "r") or die("ERROR: Cannot open the file.");
        
    /* Some code to be executed */
        
    // Closing the file handle
    fclose($handle);
} else{
    echo "Error: File does not exist.";
}
?>

PHP File Read – fread()

In the previous sections, you have understood how to open and close the file in PHP. Now in this section, you will learn about how to read a file. You can read a single character to a single word or even the entire file in a single operation.

The fread() function is used to read the specific number of characters from a file.

Syntax

The basic syntax of fread() is as below.

fread(file handle, length in bytes)

HERE,

  • “fread” is name of the PHP function to read the file.
  • “file handle” refers the file pointer resource.
  • “length in bytes” – length of the file needs to be read.

Example

file: fileread.php

<?php
$file = "file.txt";
 
// Check the existence of file
if(file_exists($file)){
    // Open the file for reading
    $handle = fopen($file, "r") or die("ERROR: Cannot open the file.");
        
    // Read fixed number of bytes from the file
    $content = fread($handle, "15");
        
    // Closing the file handle
    fclose($handle);
        
    // Display the file content 
    echo $content;
} else{
    echo "ERROR: File does not exist.";
}
?>

In the above example, we have open a file name “file.txt” for reading and read 15 bytes from
the file using fread() function.

File: file.txt

Welcome to Tutorials Book!

Output

Only 15 bytes of the text has been displayed as part of the output.

Welcome to Tuto

Reading the entire contents of file

In our previous example. we have already seen how to ready a specific number of bytes from a file. Now you will see how to read the entire file in one go.
You can use fread() function along with filesize() function to read the entire content of file at once. The filesize() function returns the size of the file in bytes.
Now let’s see our previous example with the function filesize().
Example 
File: fileread2.php
<?php
$file = "file.txt";
 
// Check the existence of file
if(file_exists($file)){
    // Open the file for reading
    $handle = fopen($file, "r") or die("ERROR: Cannot open the file.");
        
    // Read fixed number of bytes from the file
    $content = fread($handle, filesize($file));
        
    // Closing the file handle
    fclose($handle);
        
    // Display the file content 
    echo $content;
} else{
    echo "ERROR: File does not exist.";
}
?>

Output

Welcome to Tutorials Book!

The easiest way to read the entire content of a file is use readfile() function. This function read the entire content of the file without opening the file.

Example

File: fileread3.php

<?php
$file = "file.txt";
 
// Check the existence of file
if(file_exists($file)){
    // Reads and outputs the entire file
    readfile($file) or die("ERROR: Cannot open the file.");
} else{
    echo "ERROR: File does not exist.";
}
?>

Output

Welcome to Tutorials Book!

PHP File Write Function: fwrite()

The fwrite() function writes the data into a new file or append the data into a existing file. The basic syntax of the fwrite() function is given below.
Syntax
fwrite(file handle, string)
HERE,
  • “fwrite(..)” is the name of the function to write data into file.
  • “file handle” is the file pointer.
  • “string” is the data to be written into the file.

Now let’s check an example of writing content in the file.

<?php
$file = "welcome.txt";

// String of data to be written
$data = "Welcome to Tutorials Book!";

// Open the file for writing
$handle = fopen($file, "w") or die("ERROR: Cannot open the file.");

// Write data to the file
fwrite($handle, $data) or die ("ERROR: Cannot write the file.");

// Closing the file handle
fclose($handle);

echo "Data written to the file successfully.";
?>

In the above example, if the file “welcome.txt” not exist, PHP will create it and write the data. If the file exist, PHP will erase the existing data and write on it. If you want to append the data instead of erasing, you can use mode a instead of w in the above example.

An alternative way to write data is using file_put_contents() function. This is the counterpart of file_get_contents function and provides easy method for writing data into file without opening the file. This function accept both filename with path and data to be written as a parameter. Below is an example-

<?php
$file = "welcome.txt";

// String of data to be written
$data = "Welcome to Tutorials Book!";

// Write data to the file
file_put_contents($file, $data) or die("ERROR: Cannot write the file.");

echo "Data written to the file successfully.";
?>

If you want to append the data instead of erasing first and then write in the file, you can use third parameter in the above example as FILE_APPEND.

<?php
$file = "welcome.txt";

// String of data to be written
$data = "Welcome to Tutorials Book!";

// Write data to the file
file_put_contents($file, $data, FILE_APPEND) or die("ERROR: Cannot write the file.");

echo "Data written to the file successfully.";
?>

 

Please get connected & share!

Advertisement