close[x]


PHP

PHP-Home PHP-Environment Setup PHP-Syntax PHP-Run PHP in XAMPP PHP-Variable PHP-Comment PHP-Datatype PHP-String PHP-Operators PHP-Decision PHP-loop PHP-Get/Post PHP-Do While loop PHP-While loop PHP-For loop PHP-Foreach loop PHP-Array PHP-Multidimensional Arrays PHP-Associative Arrays PHP-Indexed Arrays PHP-Function PHP-Cookies. PHP-Session PHP-File upload PHP-Email PHP-Data & Time PHP-Include & Require PHP-Error PHP-File I/O PHP-Read File PHP-Write File PHP-Append & Delete File PHP-Filter PHP-Form Validation PHP-MySQl PHP-XML PHP-AJAX



learncodehere.com




PHP - Files and I/O

File handling is needed for any application.

PHP has several functions for opening, creating, reading, uploading,editing and closing files.

  • Opening a file
  • Reading a file
  • Writing a file
  • Closing a file

  • PHP - Opening and Closing Files

    The PHP fopen() function is used to open a file.

    It requires two arguments stating first the file name and then mode in which to operate.

    Files modes can be specified as one of the six options in this table.

    Mode Description
    r

    Opens the file for reading only. It places the file pointer at the beginning of the file.

    r+

    Opens the file for reading and writing.It places the file pointer at the beginning of the file.

    w

    Opens the file for writing only. It places the file pointer to the beginning of the file and truncates the file to zero length. If file is not found, it creates a new file.

    w+

    Opens the file for reading and writing only. It places the file pointer to the beginning of the file and truncates the file to zero length. If file is not found, it creates a new file..

    a

    Opens the file for writing only. It places the file pointer to the end of the file. If file is not found, it creates a new file

    a+

    Opens the file for reading and writing only.It places the file pointer to the end of the file. If file is not found, it creates a new file.


    PHP Open File - fopen()

    The PHP fopen() function is used to open a file.

    Syntax : Open File

    
     resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )  
                    

    Lets put this into example.

    Example : Open File

    
    <?php  
    $myfile = fopen("c:\\folder\\file.txt", "r");  
    ?> 


    PHP Close File - fclose()

    The PHP function is used to close an open file.

    Syntax : Close File

    
     fclose($filename);  
                    

    Lets put this into example.

    Example : Close File

    
    <?php  
    $myfile = fopen("c:\\folder\\file.txt", "r"); 
    // some code to be executed....
    fclose($myfile); 
    ?>
    

    It's a good programming practice to close all files after you have finished with them.