PHP : File Create/Write

Creating and writing to files in PHP is straightforward. Here's how you can create a new file and write data to it:

1. Creating a File:

You can create a new file using fopen() with the mode w (write mode). If the file already exists, it will be truncated (emptied), so be careful when using this mode.


$filename = "newfile.txt";
$file = fopen($filename, "w") or die("Unable to create file!");

 

2. Writing to a File:

You can write to the file using fwrite(). This function takes the file handle and the string you want to write.


$txt = "This is some text to write to the file.\n";
fwrite($file, $txt);

$txt = "Another line of text.\n";
fwrite($file, $txt);

// You can write variables as well
$name = "John Doe";
$age = 30;
fwrite($file, "Name: $name, Age: $age\n");

// Close the file when done
fclose($file);

 

Complete Example:

Here's a complete example that creates a new file named "newfile.txt" and writes some content to it:


<?php
$filename = "newfile.txt";
$file = fopen($filename, "w") or die("Unable to create file!");

$txt = "This is some text to write to the file.\n";
fwrite($file, $txt);

$txt = "Another line of text.\n";
fwrite($file, $txt);

$name = "John Doe";
$age = 30;
fwrite($file, "Name: $name, Age: $age\n");

fclose($file);
echo "File '$filename' created and written successfully.";
?>

 

Appending to a File:

If you want to add content to an existing file without truncating it, you can open the file in append mode a.


$filename = "existingfile.txt";
$file = fopen($filename, "a") or die("Unable to open file!");

$txt = "This text will be appended to the file.\n";
fwrite($file, $txt);

fclose($file);
 

In this example, a mode ensures that any new content is added to the end of the file, preserving existing content.

Remember to handle errors and permissions properly, especially when creating or writing to files. It's a good practice to check if the file was successfully opened before attempting to write to it.