Part 6: Printing to Files with PHP


  1. In this example, you use the PHP file_put_contents() function. Briefly describe this function.
  2. The file_put_contents() function writes a string to a file. It follows a specific ruleset when accessing a file:

    • If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of *filename*.
    • Create the file if it does not exist.
    • Open the file.
    • Lock the file if LOCK_EX is set.
    • If FILE_APPEND is set, move to the end of the file. Otherwise, clear the file content.
    • Write the data into the file.
    • Close the file and release any locks.
    The function returns the number of characters written into the file on success, or FALSE on failure.

  3. What is a CSV file? Why would you want to use one?
  4. A CSV file is a Comma Separated Value file. This type of file can be opened with any spreadsheet program, and the information between comma delimiters will be placed into separates cells.

notepad++ Example Program

The link above is the sample code created with Eli's demonstration of printing to files with PHP. The link goes to an HTML form which accepts a user's name and email address. Once the user hits submit, it will go to a PHP page will thank them for submitting their information. The first iteration of this program wrote the information to a .html file that could be viewed in the browser, but the current iteration above writes the information to a .csv file. The CSV file will display names in one column of cells, and email addresses in another column. All of the information is appended, so that the file is not cleared every time it is submitted.