PHP File Handling

Posted by tutor | Posted in PHP Tutorial | Posted on 09-08-2010-05-2008

0

Creating a file

In PHP the fopen function is used to create files.

It takes two parameters. The first parameter of this function contains the name of the file to be opened and the second parameter specifies the mode in which a file should be opened:

Fopen searches for a file, if it already exists then the file will be pened, otherwise a new file with the given name will be created and opened. But if you are using fopen to create a file then you must use the write or append mode in the fopen command.

Opening a File

The fopen() function is used to open files in PHP.

    div class=”example”>
    For eg

    <html>
    <body>
    <?php
    $file=fopen(“welcome.txt”,”r”);
    ?>
    </body>
    </html>

The file may be opened in one of the following modes:

    Modes Description
    r Read only. Starts at the beginning of the file
    r+ Read/Write. Starts at the beginning of the file
    w Write only. Opens and clears the contents of file; or creates a new file if it doesn’t exist
    w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn’t exist
    a Append. Opens and writes to the end of the file or creates a new file if it doesn’t exist
    a+ Read/Append. Preserves file content by writing to the end of the file
    x Write only. Creates a new file. Returns FALSE and an error if file already exists
    x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists

If the fopen() function is unable to open the specified file or the file is not found, it returns 0 (false).

The following example generates a message if the fopen() function is unable to open the specified file:

    For eg:

    <html>
    <body>
    <?php
    $file=fopen(“welcome.txt”,”r”) or exit(“Unable to open file!”);
    ?>
    </body>
    </html>

If you want to get information out of a file, like search an e-book for the occurrences of “cheese”, then you would open the file for read only.

If you wanted to write a new file, or overwrite an existing file, then you would want to open the file with the “w” option. This would wipe clean all existing data within the file.

Closing a File

The fclose() function is used to close an open file. Every time we open a file we should close it after the work is done. In PHP it is not critical to close all your files after using them because the server will close all files after the PHP code finishes execution. However a good programming practice is to close all the files and free all the resources which were being used in the program before you exit from the program.

    For eg:

    <?php
    $file = fopen(“test.txt”,”r”);
    //some code to be executed
    fclose($file);
    ?>

Write a comment

Twitter Users
Enter your personal information in the form or sign in with your Twitter account by clicking the button below.