HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP File Create / Write

Beyond reading files, PHP allows you to create new files and write data to them. This is essential for logging, generating reports, or saving user configurations on the server.


1. Creating a File

The fopen() function is also used to create a file. If you use "w" (write) or "a" (append) on a file that does not exist, PHP will create it for you.

<?php
    $myfile = fopen("testfile.txt", "w") or die("Unable to open file!");
?>

2. Writing to a File - fwrite()

The fwrite() function is used to write to a file. It takes two parameters: the file handle and the string to be written.

<?php
    $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
    $txt = "John Doe\n";
    fwrite($myfile, $txt);
    $txt = "Jane Doe\n";
    fwrite($myfile, $txt);
    fclose($myfile);
?>

3. Overwriting vs. Appending

Selection of the correct mode is critical to avoid data loss.

Mode Behavior
"w" Overwrites existing content. Pointer starts at the beginning.
"a" Appends data. Pointer starts at the end of the file. Existing content is preserved.

Example: Appending to a File

<?php
    $myfile = fopen("log.txt", "a") or die("Unable to open file!");
    $txt = "New login at " . date("H:i:s") . "\n";
    fwrite($myfile, $txt);
    fclose($myfile);
?>
Server Permissions: To create or write to a file, the PHP process must have write permissions for the directory. If you get an error, check your folder's CHMOD settings.
Warning: Opening a file with the "w" mode will erase all existing content in that file immediately. Always double-check before using it!
Pro Tip: Use \n or PHP_EOL to add new lines to your text file, making it human-readable when opened in a text editor.

Key Takeaways

  • fopen() creates a file if it doesn't exist (in w/a modes).
  • fwrite() is the standard function for writing data.
  • Use "w" to start fresh and "a" to add to existing data.
  • Ensure correct directory permissions for the PHP user.
  • Always close file handles to prevent memory bloat.