PHP File Create/Write

In PHP, you can create and write to a file using functions like fopen(), fwrite(), and fclose(). Here's a simple example that creates a file called example.txt and writes some text into it:

PHP Code Example

<?php // Define the file name $filename = "example.txt";
// Open the file for writing (w mode will create the file if it doesn't exist or overwrite it) $file = fopen($filename, "w");
// Check if the file opened successfully if ($file) {
// Text to write $content = "Hello, this is a test file!\nWritten with PHP.";
// Write to the file fwrite($file, $content);
// Close the file fclose($file); echo "File '$filename' created and written successfully."; } else { echo "Error: Unable to open the file."; } ?>

Notes:

  • "w" mode truncates the file to zero length or creates a new file if it doesn't exist.

  • Use "a" mode instead if you want to append to an existing file.

  • Make sure the directory is writable by your PHP script (check permissions).