PHP Tutorial


PHP 7 File Handling

Author:- w3alert.com
Updated Date:-05-02-2020

PHP File Handling

Files are used to storing data and information such as: Programs, Images, Text, PDF, etc.

PHP File Handling allows us to access and manipulate the file in which we can create file, read file, write file, append file, delete file, and close file.

The file system provides a concept for initializing specific data using a variety of file formats. Through this concept, you will retrieve data from disk files, XML documents, and many other data sources.

PHP file handling support many types of formats that include:

File.txt
File.gif, file.jpg
File.csv
File.log
File.custom_extension i.e. file.xyz
Files provide a sustainable cost-effective data storage solution for simple data compared to databases that require other software and skills to manage a DBMS system.
we want to collect simple data such as server logs for later retrieval and analysis
we want to save the program settings ie program.ini

PHP File Handling Functions

PHP provides a convenient method to work with files through its rich collection of built-in functions.

Operating systems such as Windows and Mac OS are not sensitive while Linux or Unix operating systems are case sensitive.

It is a good practice to adopt a naming conversion for file naming only such as naming that ensures maximum cross-platform compatibility.

PHP has the most important functions to work with file handling. Those functions are:

PHP Open File: fopen()

The fopen() function is a built-in function in PHP which is used to open a file or URL.

Syntax:

fopen ( file, mode, include_path, context );

There are four parameters in PHP fopen() Open File Function:

File: It is a necessary parameter that specifies the file.

Mode: It is a necessary parameter that specifies the access type of the file.

It can have the following reasonable values:

  • 'r': It signifies the open file in Read-only Mode; It places the file pointer at the beginning of the file.
  • 'r+': It signifies the open file in Read/Write Mode; It places the file pointer at the beginning of the file.
  • 'w': It signifies the open file in Write only Mode; It places the file pointer at the beginning of the file and truncate the file to zero length. if the file does not found, attempt to create it.
  • 'w+': It signifies the open file in Read/Write Mode; It places the file pointer at the beginning of the file and truncates the file to zero length. if the file does not found, attempt to create it.
  • 'a': It signifies the open file in Write only Mode; It places the file pointer at the end of the file and if the file does not found, attempt to create it. In this mode, fseek() has no effect, write are always appended.
  • 'a+': It signifies the open file in Read/Write Mode; It places the file pointer at the end of the file and If the file does not found, attempt to create it. In this mode, fseek() only affects the reading position, write is always appended.
  • 'x': It signifies the creates and open the file in Write only Mode; It places the file pointer at the beginning of the file. If the file already found, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not found, attempt to create it.
  • 'x+': It signifies the creates and open file in Read/Write Mode; otherwise, it has the same process as 'x'.
  • 'c': It signifies the open file in Read/Write Mode. If the file does not found, it is created. If the file founds, it is neither truncated ( as opposed to 'w' ), nor the call to this function fails ( as is the case with 'x' ). It places the file pointer at the beginning of the file This may be useful if it's desired to make an advisory lock ( see flock() ) before attempting to adjust the file, as using 'w' could truncate the file before the lock was taken ( if truncation is desired, ftruncate() can be used after the lock is requested).
  • 'c+': It signifies the open file in Read/Write Mode. otherwise, it has the same process as 'c'.
  • 'e': Set the close-on-exec flag on the opened file descriptor. only available in PHP complied on POSIX.1-2008 conform systems.

Include_path: Include_path is an optional parameter. Set this parameter '1' or TRUE if we want to search the file in the PHP include path.

Context: Context is also an optional parameter that is used to set the behavior of the file.

The most important things to remember:

  • Different operating system families have different line-ending conventions. When you write a text file and want to insert a line break, You need to use the current line-ending character(s) for your operating system. Unix based system use \n as the line ending character, Windows-based system use \r\n as the line ending characters and Macintosh-based system use \r as the line ending characters.
  • Windows provides a text-mode translation flag (t) that will transparently translate \n to \r\n when working with a file. Conversely, you can also use 'B' to force binary mode, which will not translate your data. To use these flags, specify 'b' and 't' as the last character of the file mode parameter.
  • You should use the 't' mode if you are working with the plain-text files and you use \n to delimit your line endings in the script, but expect your files to be readable with applications such as notepad. You should use the ‘b’ flag when opening files with fopen() in all cases.

Note: The fopen () function is used in both situations to open or create files. When in PHP, the file is opened using the fopen () function, it will create the file if the opened file is not found. In which it will see that the file has been opened for writing (w) or appending (a).

Example: Let's create a program to open files with the PHP fopen() function.

Create a program to create and open a file. It is shown below:

First, create and save a text file ( w3alert.txt ). 

    PHP = Hypertext Preprocessor.

    HTML = Hyper Text Markup Language.

    CSS =  Cascading Style Sheets.

    AJAX = Asynchronous JavaScript and XML.

Then create a program to open the file.

    <?php 

    $file = "w3alert.txt";
    
    $open_file = fopen( "$file", "r" );

        if ($open_file) {

            echo "The File is Run Position.";

        } else {

            echo "The File does not found.";

        }
    
    ?> 

PHP Write File: fwrite()

In PHP, The fwrite () function can be used to create new files or to add text to existing files. The arguments for the fwrite() function are the file pointer and the text to be written to the file. It may contain an optional third argument, where the length of the written text is specified.

Syntax:

    fwrite( file, text );

There are two parameters in the PHP fwrite() function.

File: It is a necessary parameter that specifies the file.

Text:  It is also a necessary parameter that specifies the written text to add text to an existing file.

Example: Let's create a program to understand the PHP fwrite() function.

Create a program to write to a file. It is shown below:

    <?php 

    $file = "w3alert.txt";

    $open_file = fopen( $file, "w" ) or die("The file does not found.");

    $text = "Welcome to w3alert.com\n";

    $file_text = fwrite( $open_file, $text ); 

    echo $file_text;

    ?>

PHP Read File: fread()

In PHP, the fread () function is used to read the contents present in a file after the fopen () function opens a file. It takes two arguments, First is file pointer and another is file size in bytes.

Syntax:

    fread( file, size );

There are two parameters in the PHP fread() function.

File: It is a necessary parameter that specifies the file.

Text:  It is also a necessary parameter that specifies the file size in bytes.

Example: Let's create a program to understand PHP fread() function.

Create a program to read the content of a file. It is shown below:

    <?php 

    $file = "w3alert.txt";

    $open_file = fopen( $file, "r" ) or die( "The file does not found." );

    $size = filesize( $file );

    $file_content = fread( $open_file, $size ); 

    echo $file_content;

    ?>

PHP Close File: fclose()

In PHP, The fclose() function is used to close a file. Its argument is a file that needs to be closed.

Syntax:

    fclose( file );

Example: Let's create a program to understand PHP fclose() function.

Create a program to close a file. It is shown below:

    <?php 

    $file = "w3alert.txt";

    $open_file = fopen( $file, "r" ) or die( "The file does not found" );

    $file_close = fclose($open_file);

        if ($file_close) {

            echo "The File is closed.";

        } else {

            echo "The File is Run Position.";

        }

    ?>