PHP File Handling

In this lesson, you will learn about File handling in PHP, and different file operations, along with examples to better understand the topic.


PHP File Handling

Online applications can accommodate file handling capabilities when files must frequently be opened and processed for various tasks. When using PHP to create a web application, we often need to work with external files to receive and write user data into files, etc. Therefore, it’s crucial to understand file handling when developing a web application.

In PHP, file management is comparable to that in other computer languages like C. To work with standard files, PHP includes a wide range of functions. These are those tasks:

  • Opening files
  • Appending files
  • Reading files
  • Creating files
  • Uploading files
  • Deleting files
  • Closing files

PHP Create and Open File

In PHP, the fopen() built-in function will create a file if it does not exist.

Basic Syntax

$file_name = 'PHPfile.txt';
opens the PHPfile.txt file or creates it implicitly.
$file_handle = fopen($file_name , 'w') or die('Sorry! cannot open file);

The example above shows that PHP uses the same method to open and create files. The filename is passed as the first argument to the fopen() method, and the second argument specifies the mode in which the file opens. However, you should maintain the mode set to w, which stands for write mode, if a file already exists and you are using fopen() to create a new one.

Additionally, the fopen() function is utilized to open files. Opening a file can be done for various reasons, including reading the file’s contents, adding new material, or updating the content already there. Let’s see various opening modes for files in the below table.

PHP file mode Symbol Description
Write mode w A new file is generated if the requested file doesn’t already exist, and if it does, it is opened to allow writing activities. The entire file’s content is destroyed when choosing this option.
Read mode r With the file pointer beginning at the beginning of the file, the file is opened in read-only mode.
Append mode a When a file is opened in write mode, its existing content is deleted. The new material is added after the earlier material.
Create Write-only file x Write-only access is granted to a brand-new file. An error is displayed if the file is already present.

PHP Read File

As mentioned above, use the function fread() to open a file in PHP. The file name variable like myphpfile to read from is contained in the function’s first parameter, and the second parameter defines the maximum number of bytes to read. The myPHPfile.txt file is read in full by the following PHP code:

Syntax

fread($myphpfile,sizeoffile("myPHPfile.txt"));

Before executing the script, let’s create a simple text file. The content of the text file is given below:

myPHPfile.txt
JavaScript. Java.
HTML. CSS.
React. Angular.
Objective C. Scala.

Read the complete and partial content of the PHP file

Use the fread() function after opening the file in “read” mode if you wish to read the complete contents. However, you can specify the size in bytes (1 byte = 1 character) in the second parameter if you only wish to print some of the file’s contents.

PHP file whole content read example

<?php
$nameofphp_file = "myphpfile.txt";
$php_file = fopen($php_filename, 'r');
$sizeoffile = filesize($nameofphp_file);
$php_filedata = fread($php_file, $sizeoffile);
?>

Output

JavaScript. Java. HTML. CSS. React. Angular. Objective C. Scala.

PHP file partial content read example

<?php
$nameofphp_file = "myphpfile.txt";
$php_file = fopen( $php_filename, 'r' );
$php_filedata = fread( $php_file, 3 );
?>

Output

Jav

Read Line by Line in PHP – fgets ()

A single line can be read from a file using the fgets() function. The following example displays the web myphpfile.txt file’s opening line.

PHP one line read example

// The file pointer has shifted to the next line following a call to the fgets() function.
<?php
$nameofphp_file = "myphpfile.txt";
$php_file = fopen( $php_filename, 'r' );
echo fgets($php_file);
?>

Output

JavaScript. Java.
Note
The file pointer advances to the following line after a call to the fgets() method; thus, if we call the fgets() function twice, we will receive two lines from the file.

Read a single character of PHP file

We can use the fgetc(), and feof() functions to output a file’s complete contents, character by character. A single character can be read from a file using the fgetc() function. The function fgetc() allows us to read a single character starting at the beginning of any file resource. So, the question is, why do we need to read a single character? This function is helpful if you need to replace a character or search for a specific character within a file’s content.

The following example reads each character of the myphpfile.txt file until the end of the file is reached.


PHP file character by character read example

<?php
$nameofphp_file = "myphpfile.txt";
while (!feof($nameofphp_file))
{
    echo fgetc($eofphp_file);
}
?>

Output

JavaScript. Java. HTML. CSS. React. Angular. Objective C. Scala.

PHP Write/ Append File

PHP Write File

An internal PHP method, fwrite(), is used to write to an opened file. The fwrite() function receives the file, the string, and the length that must be written as parameters and returns the number of bytes written on success or FALSE on failure. The fwrite() function terminates either when it reaches the specified length passed as a parameter or when it reaches the end of the file, whichever occurs first.

Basic Syntax

fwrite (File, String, Length)

Three parameters are accepted by PHP’s fwrite() method.

  • File: This required parameter identifies the file.
  • String: This required argument indicates the string written.
  • Length: This optional parameter specifies the maximum number of bytes written.

Return Value: If successful, it returns the total number of bytes written; otherwise, it returns False.

Since it is binary-safe, the fwrite() function can write binary data, such as pictures and character data. The fwrite() will add data to the end of the file’s content if writing operations are performed twice on the file pointer.

Writing data to Php file example

<?php
$myphpfile = fopen("php_file.txt", "w");
$filetxt = "PHP tutorial\n";
fwrite($myphpfile, $filetxt);
$filetxt = "Python tutorial\n";
fwrite($myphpfile, $filetxt);
fclose($myphpfile);
?>

Output

PHP tutorial
Python tutorial

We can demonstrate what occurs when we open an existing file for writing. We will begin with an empty file after erasing the current data. In the example below, we open the file php_file.txt, add some new data, and then save it.

Erasing and writing the data to file example

<?php
$myphpfile = fopen("php_file.txt", "w");
$filetxt = "C tutorial\n";
fwrite($myphpfile, $filetxt);
$filetxt = "Java tutorial\n";
fwrite($myphpfile, $filetxt);
fclose($myphpfile);
?>

Output

C tutorial
Java tutorial

Now, let’s open the php_file.txt file. Neither “PHP tutorial” nor “Python tutorial” is there—all left is the information we just typed.


PHP Appending data to file

Using the “a” mode, you can add data to a file. When a file is in “a” mode, the text is added to the end of the file, whereas when a file is in “w” mode, the previous content is overwritten. Open ” php_file.txt,” our previously created file, and add the following text to it:

Appending the data to file example

<?php
$myphpfile = fopen("php_file.txt", "a");
$filetxt = "C++ tutorial\n";
fwrite($myphpfile, $filetxt);
$filetxt = "Basic tutorial\n";
fwrite($myphpfile, $filetxt);
fclose($myphpfile);
?>

Output

C tutorial
Java tutorial
C++ tutorial
Basic tutorial

PHP Close File

A file pointed to by an open file pointer can be closed using PHP’s built-in fclose() method. It accepts the argument for the file that has to be closed and closes that file. If fclose() succeeds, it returns true; if it fails, it returns false.

Basic Syntax

fclose(bool, $file)

The only parameter that the PHP fclose() method allows is $file. This argument specifies the file that has to be closed.

Return Value: On success, it returns true; on failure, it returns false.

Errors & Exceptions: It must first be closed using the function before reading a file’s contents using the fclose() function.

Note
PHP’s fclose() method is ineffective with remote files and only functions with files that the server’s filesystem can access.

PHP close file example

<?php
$nameofphp_file = "myphpfile.txt";
$php_file = fopen( $php_filename, 'r' );
fclose ( $php_file);
?>

Output

True

PHP Delete File

Utilize the unlink() function to remove a file.

Basic Syntax

unlink ( string $nameoffile , resource $context = ? ) : bool

There are two parameters for the unlink() function: The whole path to the file you want to remove is $nameoffile. A legitimate context resource is $context. When the file is successfully deleted, the unlink() function returns true; otherwise, it returns false.

If the $nameoffile is empty, the unlink() function also prints a warning and returns false.

Example

<?PHP
$php_file = 'myphpfile.txt';
if (unlink($php_file))
{
    echo 'The file ' . $php_file . ' deleted successfully!';
}
else
{
    echo 'error deleting ' . $php_file;
}
?>

This concludes the PHP File Handling lesson. In the next lesson, you will learn about File Upload in PHP.