English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic PHP Tutorial

Advanced PHP Tutorial

PHP & MySQL

PHP Reference Manual

PHP File (File)

In this tutorial, you will learn how to dynamically create, access (or read), and manipulate files using PHP's file system functions.

Use PHP to process files

Since PHP is a server-side programming language, it allows you to use files and directories stored on the web server. In this tutorial, you will learn how to create, access, and operate files on the web server using PHP file system functions.

Open files using PHP fopen() function

To use files, you first need to open the file. The PHP fopen() function is used to open files. The basic syntax of this function can be given in the following way:

fopen(filename, mode)

The first parameter passed to fopen() specifies the name of the file to be opened, and the second parameter specifies the mode in which the file should be opened. For example:

<?php
$handle = fopen("data.txt", "r");
?>
Test and see‹/›

You can open a file in one of the following ways:

ModeWhat can it do
rOpen file for read only
r+Open file for read and write
wOpen file for writing only, and clear the file content. If the file does not exist, PHP will try to create it.
w+Open file for read and write, and clear the file content. If the file does not exist, PHP will try to create it.
aAppend. Open file for writing only. By writing to the end of the file, the content of the file is preserved. If the file does not exist, PHP will try to create it.
a+Read/Append. Open file for read and write. By writing to the end of the file, the content of the file is preserved. If the file does not exist, PHP will try to create it.
xOpen file for writing only. If the file already exists, it returns False and generates an error. If the file does not exist, PHP will try to create it.
x+Open file for read and write; otherwise, its behavior is the same as "x".

If you try to open a non-existent file, PHP will generate a warning message. Therefore, to avoid these error messages, you should use the PHP file_exists() function to perform a simple check to see if a file or directory exists before trying to access it.

<?php
$file = "data.txt";
 
//Check if the file exists
if(file_exists($file)){
    // Attempt to open the file
    $handle = fopen($file, "r");
} else {
    echo "ERROR: File does not exist.";
}
?>
Test and see‹/›

Tip:Operations on files and directories are prone to errors. Therefore, it is a good habit to implement some form of error checking so that your script can handle errors gracefully if they occur. Please refer to relatedPHP error handlingtutorial.

Using PHP fclose() function to close file

After using the file, it needs to be closed. The fclose() function is used to close the file, as shown in the following example:

<?php
$file = "data.txt";
 
//Check if the file exists
if(file_exists($file)){
    //Opening the file to be read
    $handle = fopen($file, "r") or die("ERROR: Cannot open the file.");
        
    /* Here is some code to be executed */
        
    //Closing the file handle
    fclose($handle);
} else {
    echo "ERROR: File does not exist.";
}
?>
Test and see‹/›

Note:Although PHP will automatically close all open files when the script terminates, it is best to close the file after all operations are performed.

Using PHP fread() function to read from file

Now that you have learned how to open and close files, in the next section, you will learn how to read data from files. PHP has several functions for reading data from files. You can read the entire file with a single operation.

Read a fixed number of characters

The fread() function can be used to read a specified number of characters from a file. You can use the basic syntax of this function.

fread(file handle, length in bytes)

This function accepts two parameters-File handle and the number of bytes to read. The following example reads from the "data.txt" file.20 bytes, including spaces. Assuming the file "data.txt" contains the text "The quick brown fox jumps over the lazy dog.".

<?php
$file = "data.txt";
 
//Check if the file exists
if(file_exists($file)){
    //Opening the file to be read
    $handle = fopen($file, "r") or die("ERROR: Cannot open the file.");
        
    //Read a fixed number of bytes from the file
    $content = fread($handle, "20);
        
    //Close the file handle
    fclose($handle);
        
    //Display file content
    echo $content;
} else {
    echo "ERROR: File does not exist.";
}
?>
Test and see‹/›

The above example will produce the following output:

The quick brown fox

Read the entire content of the file

The fread() function can be combined with the filesize() function to read the entire file at once. The filesize() function is used to: return the size of the file in bytes.

<?php
$file = "data.txt";
 
//Check if the file exists
if(file_exists($file)){
    //Opening the file to be read
    $handle = fopen($file, "r") or die("ERROR: Cannot open the file.");
        
    //Reading the entire file
    $content = fread($handle, filesize($file));
        
    //Closing the file handle
    fclose($handle);
        
    //Display file content
    echo $content;
} else {
    echo "ERROR: File does not exist.";
}
?>
Test and see‹/›

The above example will produce the following output:

The quick brown fox jumps over the lazy dog.

The simplest way to read the entire content of a file in PHP is to use the readfile() function. This function allows you to read the content of the file without opening it. The following example will generate the same output as the above example:

<?php
$file = "data.txt";
 
//Check if the file exists
if(file_exists($file)){
    //Read and output the entire file
    readfile($file) or die("ERROR: Cannot open the file.");
} else {
    echo "ERROR: File does not exist.";
}
?>
Test and see‹/›

The above example will produce the following output:

The quick brown fox jumps over the lazy dog.

Another method to read the entire content of a file without opening it is to use the file_get_contents() function. This function accepts the file name and path and reads the entire file into a string variable. Here is an example:

<?php
$file = "data.txt";
 
//Check if the file exists
if(file_exists($file)){
    // Read the entire file into a string
    $content = file_get_contents($file) or die("ERROR: Cannot open the file.");
        
    //Display file content
    echo $content;
} else {
    echo "ERROR: File does not exist.";
}
?>
Test and see‹/›

Another method to read all the data from a file is the PHP file() function. It works similarly to the file_get_content() function, but it returns the file content as an array of lines instead of a single string. Each element of the returned array corresponds to a line in the file.

To process file data, you need to useforeach loopTraverse the array. This is an example that reads the file into an array and then displays it using a loop:

<?php
$file = "data.txt";
 
//Check if the file exists
if(file_exists($file)){
    //Read the entire file into an array
    $arr = file($file) or die("ERROR: Cannot open the file.");
    foreach($arr as $line){
        echo $line;
    }
} else {
    echo "ERROR: File does not exist.";
}
?>
Test and see‹/›

Write to the file using the PHP fwrite() function

Similarly, you can use the PHP fwrite() function to write data to a file or append to an existing file. The basic syntax of the function can be given as follows:

fwrite(file handle, string)

The fwrite() function accepts two parameters—file handle and the string of data to be written, as shown in the following example:

<?php
$file = "note.txt";
    
//The string of data to be written
$data = "The quick brown fox jumps over the lazy dog.";
    
//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.");
    
//Close the file handle
fclose($handle);
    
echo "Data has been successfully written to the file.";
?>

In the above example, if the "note.txt" file does not exist, PHP will automatically create the file and write data to it. However, if the "note.txt" file already exists, PHP will erase the content of the file (if any) before writing new data, but if you only want to append to the file and retain the existing content, please use the example aboveMode a instead of w.

Another method is to use the file_put_contents() function. It is the corresponding function to file_get_contents(), providing a convenient way to write data to a file without opening it. The function accepts the file name and path as well as the data to be written to the file. Here is an example:

<?php
$file = "note.txt";
    
//The string of data to be written
$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.");
    
echo "Data has been successfully written to the file.";
?>

If the file specified in the file_put_contents() function already exists, by default, PHP will overwrite it. To retain the content of the file, you can pass the special FILE_APPEND flag as the third parameter to the file_put_contents() function. It will simply append new data to the file instead of overwriting it. Here is an example:

<?php
$file = "note.txt";
    
//The string of data to be written
$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.");
    
echo "Data has been successfully written to the file.";
?>

Use PHP rename() function to rename a file

You can use PHP's rename() function to rename a file or directory as shown below:

<?php
$file = "file.txt";
 
//Check if the file exists
if(file_exists($file)){
    //Try to rename the file
    if(rename($file, "newfile.txt")){
        echo "File renaming was successful.";
    } else {
        echo "Error: Cannot rename file.";
    }
} else {
    echo "Error: File does not exist.";
}
?>

Use PHP unlink() function to delete a file

You can use PHP's unlink() function to delete a file or directory as shown below:

<?php
$file = "note.txt";
 
//Check if the file exists
if(file_exists($file)){
    //Try to delete the file
    if(unlink($file)){
        echo "File has been successfully deleted.";
    } else {
        echo "Error: Cannot delete file.";
    }
} else {
    echo "Error: File does not exist.";
}
?>

In the next chapter, we will learn aboutParsing the directory or folder'sMore information.

PHP file system functions

The following table summarizes some other useful PHP file system functions that can be used for dynamic reading and writing files.

Function
Description
fgetc()Read a character at a time.
fgets()Read a line at a time.
fgetcsv()Read a line with comma-separated values.
filetype()Return the type of the file.
feof()Check if the end of the file has been reached.
is_file()Check if the file is a regular file.
is_dir()Check if the file is a directory.
is_executable()Check if the file is executable.
realpath()Return the normalized absolute path name.
rmdir()Delete an empty directory.

Please refer to the PHP file system reference to get other useful PHP file system functions.