File Handling in PHP: Scene 1

Like other languages, PHP also has file handling as an important part of web applications that allows us to manipulate files using several functions such as creating, reading, writing, deleting and so on.

The following is a list of functions that can be used to manipulate the files in PHP:

  • Create
  • Open
  • Close
  • Read
  • Write
  • Append
  • Delete

image
Cautions

You need to be very careful when manipulating files because if you do something wrong then a lot of damage can be happen, like deleting the contents of the file by mistake, editing the wrong file, filling garbage data in the hard-drive, writing the content in the wrong file and so on.

Now let's explain all the functions briefly.

Create and Open

The function fopen() is used to open as well as create a file.

Syntax example:

    <?php
    $New_file = 'file.txt';
    $handle = fopen($New_file, 'w'); //implicitly creates file
    ?>

    <?php
    $New_file = 'file.txt';
    $handle = fopen($New_file, 'w') or die('Cannot open file: '.$New_file); //open file for writing ('w','r','a')...
    ?>

Close

The function fclose() is used to close an open file after finishing your work.

Syntax example:

    <?php
    $New_file = 'file.txt';
    $handle = fopen($New_file, 'w');
    //do whatever you want to do with open file
    fclose($handle); // close the file
    ?>

Read

The function fread() is used to read the contents of the file. It needs two arguments, the resource and file size.

Syntax example:

    <?php
    $New_file = 'file.txt';
    $handle = fopen($New_file, 'r');
    $data = fread($handle,filesize($New_file)); //now you can read the file
    ?>

Write

The function fwrite() is used to write the contents of the string into a file.

Syntax example:

    <?php
    $New_file = 'file.txt';
    $handle = fopen($New_file, 'w');
    $data =’the data is to be written’; //writing
    fwrite($handle, $data);
    ?>

Append

The function fopen() is also used to append the contents into a file, but in a different way. It uses "a" or "a+" mode in fopen() the function.

Syntax example:

    <?php
    $New_file = 'file.txt';
    $handle = fopen($New_file, 'a');
    $data = 'New data line 1';//append this line into file
    fwrite($handle, $data);
    $new_data = "\n".'New data line 2';//append this too
    fwrite($handle, $new_data);
    ?>

Delete

The function unlink() is used to delete the file.

Syntax example:

    <?php
    $New_file = 'file.txt';
    unlink($New_file);//delete the file
    ?>

The details about all the functions will be discussed in the next part of this article and that will be here as soon as possible, until then.

Thank you, keep learning and sharing.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now