File Create Or Write in PHP
? File Create or Write in PHP
In PHP, you can create and write to files using built-in file system functions. This is especially useful for logs, saving form data, generating reports, etc.
? fopen() + fwrite() + fclose()
Here’s the basic process:
<?php$myfile = fopen("example.txt", "w") or die("Unable to open file!");fwrite($myfile, "Hello, world!\nThis is a test.");fclose($myfile);?>? Explanation:
fopen("example.txt", "w"):
Opens the file for writing. If the file doesn’t exist, it creates it. If it does exist, it clears the content.fwrite():
Writes text into the file.fclose():
Closes the file (always a good practice).
? File Modes
| Mode | Description |
|---|---|
"w" | Write only. Creates new or erases old. |
"a" | Append. Adds to the end of the file. |
"x" | Create new file only. Fails if file exists. |
"w+" | Read/Write. Erases old content. |
"a+" | Read/Append. Writes at the end. |
"x+" | Read/Write. New file only. |
?? Example: Append to a File
<?php$myfile = fopen("log.txt", "a") or die("Unable to open file!");fwrite($myfile, "New log entry: " . date("Y-m-d H:i:s") . "\n");fclose($myfile);?>? Example: Create File and Write User Input (Form)
<!-- form.html --><form action="write.php" method="post"> Your Name: <input type="text" name="name"> <input type="submit"></form><?php// write.php$name = $_POST['name'];$file = fopen("names.txt", "a");fwrite($file, $name . "\n");fclose($file);echo "Name saved!";?>?? Tips
Use
file_put_contents("file.txt", "text")for quick writing.Always check if
fopen()fails.Handle file permissions properly (read/write access).