PHP File Create/Write

Creating and writing data to files

✍️ What is File Creation and Writing?

Creating and writing files in PHP allows you to save data permanently on the server. You can create new files, overwrite existing content, or append data to files for logs, user data, and configurations.


<?php
// Simple file writing
file_put_contents("message.txt", "Hello World!");
echo "File created and written!";
?>
                                    

File Writing Methods

file_put_contents()

The easiest way to write data to a file. Creates the file if it doesn't exist and overwrites existing content automatically.

<?php
file_put_contents("note.txt", "My note");
?>
📝

fwrite()

Write data to an opened file with more control. Useful when you need to write multiple times or handle large data efficiently.

<?php
$file = fopen("data.txt", "w");
fwrite($file, "Content here");
fclose($file);
?>

Append Mode

Add new content to the end of existing files without deleting old data. Perfect for logs and records that grow over time.

<?php
file_put_contents("log.txt", "New entry\n", FILE_APPEND);
?>
🔒

File Locking

Prevent multiple processes from writing to the same file simultaneously. Ensures data integrity when multiple users access files.

<?php
file_put_contents("shared.txt", "Data", LOCK_EX);
?>

🔹 Creating and Writing with file_put_contents()

The simplest way to create and write to files:

<?php
// Create new file and write content
$content = "Welcome to PHP file handling!";
file_put_contents("welcome.txt", $content);

echo "File created successfully!";
?>

Output:

File created successfully!

File "welcome.txt" now contains: "Welcome to PHP file handling!"

🔹 Writing with fopen() and fwrite()

More control over the writing process:

🔸 Basic Writing

<?php
// Open file for writing (creates if doesn't exist)
$file = fopen("report.txt", "w");

// Write content
fwrite($file, "Report Title\n");
fwrite($file, "Generated on: " . date("Y-m-d") . "\n");
fwrite($file, "Data: Sample information");

// Close file
fclose($file);

echo "Report created!";
?>

🔸 Writing Multiple Lines

<?php
$file = fopen("list.txt", "w");

$items = ["Apple", "Banana", "Orange", "Grape"];

foreach($items as $item) {
    fwrite($file, $item . "\n");
}

fclose($file);
echo "List saved!";
?>

🔹 Appending to Existing Files

Add content without deleting existing data:

🔸 Using FILE_APPEND Flag

<?php
// Add new entry to log file
$logEntry = date("Y-m-d H:i:s") . " - User logged in\n";
file_put_contents("activity.log", $logEntry, FILE_APPEND);

echo "Log entry added!";
?>

🔸 Using Append Mode with fopen()

<?php
// Open file in append mode
$file = fopen("comments.txt", "a");

$newComment = "Great article! - John\n";
fwrite($file, $newComment);

fclose($file);
echo "Comment added!";
?>

🔹 File Writing Modes

Different modes for different purposes:

Writing Modes:

  • w - Write mode: Creates new file or overwrites existing
  • w+ - Write and read: Overwrites and allows reading
  • a - Append mode: Adds to end of file
  • a+ - Append and read: Adds to end and allows reading
  • x - Exclusive creation: Creates only if file doesn't exist
<?php
// Overwrite mode
$file1 = fopen("new.txt", "w");
fwrite($file1, "This replaces everything");
fclose($file1);

// Append mode
$file2 = fopen("existing.txt", "a");
fwrite($file2, "This is added to the end");
fclose($file2);

// Exclusive mode (fails if file exists)
$file3 = fopen("unique.txt", "x");
if($file3) {
    fwrite($file3, "Created only if didn't exist");
    fclose($file3);
}
?>

🔹 Writing Arrays to Files

Save array data to files:

<?php
// Array of user data
$users = [
    "John Doe",
    "Jane Smith",
    "Bob Johnson"
];

// Write each item on a new line
$content = implode("\n", $users);
file_put_contents("users.txt", $content);

echo "Users saved!";
?>

🔹 Writing CSV Files

Create CSV files for spreadsheet data:

<?php
$file = fopen("students.csv", "w");

// Write header
fputcsv($file, ["Name", "Age", "Grade"]);

// Write data rows
fputcsv($file, ["Alice", 20, "A"]);
fputcsv($file, ["Bob", 22, "B"]);
fputcsv($file, ["Charlie", 21, "A"]);

fclose($file);
echo "CSV file created!";
?>

Result (students.csv):

Name,Age,Grade
Alice,20,A
Bob,22,B
Charlie,21,A

🔹 Practical Example: Contact Form Logger

Save form submissions to a file:

<?php
// Simulate form data
$name = "John Doe";
$email = "[email protected]";
$message = "Hello, I have a question.";

// Create log entry
$timestamp = date("Y-m-d H:i:s");
$logEntry = "[$timestamp] Name: $name | Email: $email | Message: $message\n";
$separator = str_repeat("-", 50) . "\n";

// Append to log file
file_put_contents("contacts.log", $logEntry . $separator, FILE_APPEND);

echo "Contact form submitted and logged!";
?>

Output:

Contact form submitted and logged!

Entry added to contacts.log

🔹 Error Handling

Check for errors when writing files:

<?php
$filename = "output.txt";
$content = "Important data";

// Try to write file
$result = file_put_contents($filename, $content);

if($result === false) {
    echo "Error: Could not write to file!";
} else {
    echo "Successfully wrote $result bytes to file!";
}
?>

🧠 Test Your Knowledge

Which flag is used to append data to a file?