Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Open, Read, Append and Close file

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 126
    Comment on it

    OPEN FILE-  fopen()

    In php file is opened by the fopen() function. The fopen() contains  two parameters. The first parameter of fopen() holds the name of the file to be opened and second parameter indicates the mode in which file is to be opened.

    E.g of fopen()-

    <!DOCTYPE html>
    <html>
    <body>
    
    <?php
    $file = fopen("testfile.txt", "r") or die("Unable to open file!");
    echo fread($file,filesize("testfile.txt"));
    fclose($myfile);
    ?>
    
    </body>
    </html>

    Suppose the testfile.txt contains:

    What is PHP?

    • PHP is an acronym for "PHP: Hypertext Preprocessor"
    • PHP is a widely-used, open source scripting language
    • PHP scripts are executed on the server
    • PHP is free to download and use

    So the same output will be shown.

     

    READ FILE- fread()

    The fread() function is used to read the file from the opened file. The first parameter shows the name of the file to be read and second parameter shows the length of the characters(how many bytes of character to be shown).

    Syntax of fread()-

    fread($file,filesize("testfile.txt"));
    

    This will show the whole data of the file.

     

    APPEND FILE-

    Append means to add content in the file. To append the file we use 'a' mode in the parameter.

    <?php
    $file = fopen("testfile.txt", "a") or die("Unable to open file!");
    $txt = "Hello\n";
    fwrite($file, $txt);
    $txt = "Hello world\n";
    fwrite($file, $txt);
    fclose($file);
    
    
    $file1 = fopen("testfile.txt", "r") or die("Unable to open file!");
    echo fread($file1,filesize("testfile.txt"));
    ?>

    The above code will add the text again and again on refreshing the page.

     

    CLOSE FILE- fclose()

    This is needed to close a file which is opened once. The file is closed by using fclose() function. The first parameter contains the name of the file to be closed and second parameter contains the mode.

    Syntax of closing the function-

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

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: