PHP File Create/Write
In PHP, you can create a new file and write data to it using the fopen()
function with the write mode and fwrite()
function.
Creating a New File
<?php
$file = fopen("newfile.txt", "w"); // Open the file for writing
if ($file) {
echo "File created successfully!";
} else {
echo "Failed to create the file.";
}
fclose($file); // Close the file
?>
Explanation: This example demonstrates how to create a new file in write mode using fopen()
. If the file does not exist, it will be created.
Writing to a File
<?php
$file = fopen("newfile.txt", "w");
if ($file) {
fwrite($file, "Hello, World!"); // Write data to the file
fclose($file); // Close the file
echo "Data written to file successfully!";
} else {
echo "Failed to open the file for writing.";
}
?>
Explanation: This example demonstrates how to open a file in write mode, write data to it using fwrite()
, and then close the file. The message confirms that the data was written successfully.