File Handling in PHP

Opening and Closing Files
Files are opened in PHP using the fopen command. The command takes two parameters, the file to be opened, and the mode in which to open the file. The function returns a file pointer if successful, otherwise zero (false). Files are opened with fopen for reading or writing.
$fp fopen("myfile.txt""r");
If fopen is unable to open the file, it returns 0. This can be used to exit the function with an appropriate message.
if ( !($fp fopen("myfile.txt""r") ) )
    exit(
"Unable to open the input file.");

Replies

  • PraveenKumar Purushothaman
    PraveenKumar Purushothaman
    File Modes

    File Modes
    The following list shows the different modes the file may be opened in.
    Mode r
    Read Only mode, with the file pointer at the start of the file.

    Mode r+
    Read/Write mode, with the file pointer at the start of the file.

    Mode w
    Write Only mode. Truncates the file (effectively overwriting it). If the file doesn't exist, fopen will attempt to create the file.

    Mode w+
    Read/Write mode. Truncates the file (effectively overwriting it). If the file doesn't exist, fopen will attempt to create the file.

    Mode a
    Append mode, with the file pointer at the end of the file. If the file doesn't exist, fopen will attempt to create the file.

    Mode a+
    Read/Append, with the file pointer at the end of the file. If the file doesn't exist, fopen will attempt to create the file.
    Note: The mode may also contain the letter 'b'. This is useful only on systems which differentiate between binary and text files (i.e.Windows. It's useless on Unix/Linux). If not needed, it will be ignored.
  • PraveenKumar Purushothaman
    PraveenKumar Purushothaman
    Closing a File

    Closing a File
    The fclose function is used to close a file when you are finished with it.
    fclose($fp);
  • PraveenKumar Purushothaman
    PraveenKumar Purushothaman
    Reading from Files

    Reading from Files
    You can read from files opened in r, r+, w+, and a+ mode. The feof function is used to determine if the end of file is true.
    if ( feof($fp) )
        echo 
    "End of file
    "
    ;
    The feof function can be used in a while loop, to read from the file until the end of file is encountered. A line at a time can be read with the fgets function:
    while( !feof($fp) ) {
        
    // Reads one line at a time, up to 254 characters. Each line ends with a newline.
        // If the length argument is omitted, PHP defaults to a length of 1024.
        
    $myline fgets($fp255);
        echo 
    $myline;
    }
    You can read in a single character at a time from a file using the fgetc function:
    while( !feof($fp) ) {
        
    // Reads one character at a time from the file.
        
    $ch fgetc($fp);
        echo 
    $ch;
    }
    You can also read a single word at a time from a file using the fscanf function. The function
    takes a variable number of parameters, but the first two parameters are mandatory. The first
    parameter is the file handle, the second parameter is a C-style format string. Any parameters
    passed after this are optional, but if used will contain the values of the format string.
    $listFile "list.txt"// See next page for file contents
    if (!($fp fopen($listFile"r")))
        exit(
    "Unable to open $listFile.");
    while (!
    feof($fp)) {
        
    // Assign variables to optional arguments
        
    $buffer fscanf($fp"%s %s %d"$name$title$age);
        if (
    $buffer == 3// $buffer contains the number of items it was able to assign
            
    print "$name $title $age
    \n"
    ;
    }
    Here is the file list.txt:
    Dave Programmer 34
    Sue Designer 21
    Lisa Programmer 29
    Nigel User 19
    You can also store the variables in an array by omitting the optional parameters in fscanf:
    while (!feof($fp)) {
        
    $buffer fscanf($fp"%s %s %d"); // Assign variables to an array
        // Use the list function to move the variables from the array into variables
        
    list($name$title$age) = $buffer;
        print 
    "$name $title $age
    \n"
    ;
    }
    You can read in an entire file with the fread function. It reads a number of bytes from a file, up to the end of the file (whichever comes first). The filesize function returns the size of the file in bytes, and can be used with the fread function, as in the following example.
    $listFile "myfile.txt";
    if (!(
    $fp fopen($listFile"r")))
        exit(
    "Unable to open the input file, $listFile.");
    $buffer fread($fpfilesize($listFile));
    echo 
    "$buffer
    \n"
    ;
    fclose($fp);
    You can also use the file function to read the entire contents of a file into an array instead of opening the file with fopen:
    $array file(‘filename.txt’);
    Each array element contains one line from the file, where each line is terminated by a newline.
  • PraveenKumar Purushothaman
    PraveenKumar Purushothaman
    Writing to Files

    Writing to Files
    The fwrite function is used to write a string, or part of a string to a file. The function takes three parameters, the file handle, the string to write, and the number of bytes to write. If the number of bytes is omitted, the whole string is written to the file. If you want the lines to appear on separate lines in the file, use the \n character.
    Note: Windows requires a carriage return character as well as a new line character, so if you're using Windows, terminate the string with \r\n. The following example logs the visitor to a file, then displays all the entries in the file.
    < ?php
    $logFile 
    "stats.txt";
    $fp fopen($logFile"a+"); // Open the file in append/read mode
    $userDetails $_SERVER[‘HTTP_USER_AGENT’]; // Create a string containing user details
    if (isset($_SERVER[‘HTTP_REFERER’]))
        
    $userDetails .= {$_SERVER[‘HTTP_REFERER’]}
    \r\n"
    ;
    else
        
    $userDetails .= "
    \r\n"
    ;
    fwrite($fp"$userDetails"); // Write the user details to the file
    rewind($fp); // Move the file pointer to the start of the file
    $entries 0;
    while(!
    feof($fp)) { // Display each line in the file
        
    $buffer fgets($fp1024);
        if (
    $buffer != "") {
            echo 
    $buffer;
            
    $entries++;
        }
    // Show a summary
    echo "There are $entries entries in the log file
    "
    ;
    fclose ($fp);
    ? >
    I have added an extra space between
    php and ? >
    so that the board doesn't hang!

You are reading an archived discussion.

Related Posts

I got this project idea today after receiving another advertisement SMS from Airtel. Since it is an effective way to reach thousands of people, SIM card companies send SMSes wildly...
Can you identify the bridges in this picture? Also state the link between them.
News: NASA scientist finds 'worm-like alien life form in meteorite' - Yahoo! News Looks like NASA's got something that they want people to believe. Dr Richard Hoove claims that he's...
Article: Why Silicon Valley Immigrant Entrepreneurs Are Returning Home Professor Vivek Wadhwa wrote in TC Blog post that immigrant silicon valley entrepreneurs were returning home and instead of creating jobs...
Got following mail from Amit, the founder of NurtureTalent - Dear Friends, We are pleased to share that with your kind support, Nurture Talent Academy, India's 1st institute for training...