🎯 Learning Objectives
- Read and write files in PHP
- Handle file uploads
- Process and save form data to files
- Work with CSV files
- Implement contact form with file storage
📁 File Functions in PHP
| Function | Description | Usage |
|---|---|---|
| fopen() | Opens a file | fopen("file.txt", "r") |
| fread() | Reads from a file | fread($file, filesize("file.txt")) |
| fwrite() | Writes to a file | fwrite($file, $data) |
| fclose() | Closes a file | fclose($file) |
| file_get_contents() | Reads entire file | file_get_contents("file.txt") |
| file_put_contents() | Writes to file | file_put_contents("file.txt", $data) |
📖 File Open Modes
| Mode | Description |
|---|---|
| r | Read only, pointer at beginning |
| w | Write only, erases existing content |
| a | Append, pointer at end |
| r+ | Read/Write, pointer at beginning |
| w+ | Read/Write, erases existing content |
| a+ | Read/Append, pointer at end |
📝 Writing to Files
Method 1: Using fopen/fwrite/fclose
<?php
// Open file for writing
$file = fopen("data.txt", "w");
// Write data
$text = "Hello, this is a test file!\n";
$text .= "PHP file handling is fun!";
fwrite($file, $text);
// Close file
fclose($file);
echo "File written successfully!";
?>
Method 2: Using file_put_contents (Easier)
<?php
$text = "Hello, this is a test file!\n";
$text .= "PHP file handling is fun!";
file_put_contents("data.txt", $text);
echo "File written successfully!";
?>
📖 Reading from Files
Method 1: Using fopen/fread/fclose
<?php
// Open file for reading
$file = fopen("data.txt", "r");
// Read file content
$content = fread($file, filesize("data.txt"));
// Close file
fclose($file);
echo $content;
?>
Method 2: Using file_get_contents (Easier)
<?php
$content = file_get_contents("data.txt");
echo $content;
?>
➕ Appending to Files
<?php
// Append new data to existing file
$newData = "\nThis line is appended!";
// Method 1: fopen with 'a' mode
$file = fopen("data.txt", "a");
fwrite($file, $newData);
fclose($file);
// Method 2: file_put_contents with FILE_APPEND flag
file_put_contents("data.txt", $newData, FILE_APPEND);
echo "Data appended successfully!";
?>
📋 Working with CSV Files
Writing to CSV
<?php
$students = [
["Ahmad", "ahmad@email.com", "20"],
["Fatima", "fatima@email.com", "22"],
["Ibrahim", "ibrahim@email.com", "21"]
];
$file = fopen("students.csv", "w");
// Write header
fputcsv($file, ["Name", "Email", "Age"]);
// Write data rows
foreach ($students as $student) {
fputcsv($file, $student);
}
fclose($file);
echo "CSV file created successfully!";
?>
Reading from CSV
<?php
$file = fopen("students.csv", "r");
echo "<table border='1'>";
while (($row = fgetcsv($file)) !== false) {
echo "<tr>";
foreach ($row as $cell) {
echo "<td>" . $cell . "</td>";
}
echo "</tr>";
}
echo "</table>";
fclose($file);
?>
💻 Complete Contact Form with File Storage
<!DOCTYPE html>
<html>
<head>
<title>Contact Form with File Storage</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
background: #f4f4f4;
}
.form-container {
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}
h2 { color: #ee5a6f; }
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input, textarea {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
textarea {
height: 100px;
resize: vertical;
}
button {
background: #ee5a6f;
color: white;
padding: 12px 30px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}
button:hover {
background: #d94860;
}
.success {
background: #d4edda;
color: #155724;
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
}
.error {
background: #f8d7da;
color: #721c24;
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
}
</style>
</head>
<body>
<div class="form-container">
<h2>Contact Us</h2>
<?php
$errors = [];
$success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate inputs
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
if (empty($name)) {
$errors[] = "Name is required";
}
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Valid email is required";
}
if (empty($subject)) {
$errors[] = "Subject is required";
}
if (empty($message)) {
$errors[] = "Message is required";
}
// If no errors, save to file
if (empty($errors)) {
$date = date("Y-m-d H:i:s");
$separator = "----------------------------------------\n";
$data = $separator;
$data .= "Date: " . $date . "\n";
$data .= "Name: " . $name . "\n";
$data .= "Email: " . $email . "\n";
$data .= "Subject: " . $subject . "\n";
$data .= "Message: " . $message . "\n";
$data .= $separator . "\n";
// Append to messages.txt file
file_put_contents("messages.txt", $data, FILE_APPEND);
// Also save to CSV for easy viewing
$csvData = [$date, $name, $email, $subject, $message];
$csvFile = fopen("messages.csv", "a");
fputcsv($csvFile, $csvData);
fclose($csvFile);
$success = "Thank you! Your message has been sent successfully.";
// Clear form
$_POST = [];
}
}
?>
<?php if (!empty($errors)): ?>
<div class="error">
<ul>
<?php foreach ($errors as $error): ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php if ($success): ?>
<div class="success">
<?php echo $success; ?>
</div>
<?php endif; ?>
<form method="POST" action="">
<div class="form-group">
<label>Name:</label>
<input type="text" name="name"
value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''; ?>">
</div>
<div class="form-group">
<label>Email:</label>
<input type="email" name="email"
value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>">
</div>
<div class="form-group">
<label>Subject:</label>
<input type="text" name="subject"
value="<?php echo isset($_POST['subject']) ? htmlspecialchars($_POST['subject']) : ''; ?>">
</div>
<div class="form-group">
<label>Message:</label>
<textarea name="message"><?php echo isset($_POST['message']) ? htmlspecialchars($_POST['message']) : ''; ?></textarea>
</div>
<button type="submit">Send Message</button>
</form>
</div>
</body>
</html>
📊 View Messages Page
<!DOCTYPE html>
<html>
<head>
<title>View Messages</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.message {
background: white;
padding: 20px;
margin-bottom: 20px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.message h3 { color: #ee5a6f; margin-top: 0; }
.meta { color: #666; font-size: 14px; margin-bottom: 10px; }
</style>
</head>
<body>
<h1>Contact Messages</h1>
<?php
// Check if file exists
if (file_exists("messages.csv")) {
$file = fopen("messages.csv", "r");
while (($row = fgetcsv($file)) !== false) {
echo "<div class='message'>";
echo "<h3>" . htmlspecialchars($row[3]) . "</h3>";
echo "<div class='meta'>";
echo "From: " . htmlspecialchars($row[1]) . " (" . htmlspecialchars($row[2]) . ")<br>";
echo "Date: " . htmlspecialchars($row[0]);
echo "</div>";
echo "<p>" . nl2br(htmlspecialchars($row[4])) . "</p>";
echo "</div>";
}
fclose($file);
} else {
echo "<p>No messages yet.</p>";
}
?>
</body>
</html>
✏️ Practice Exercises
- Create a guest book where visitors can sign their name
- Build a simple blog that saves posts to a text file
- Create a todo list that saves tasks to CSV
- Build a feedback form with file storage
- Create a page counter that tracks visits in a file
✅ Best Practices
- ✓ Always close files after opening them
- ✓ Check if file exists before reading
- ✓ Use FILE_APPEND to add to existing files
- ✓ Validate data before writing to files
- ✓ Use CSV for structured data
- ✓ Sanitize data with htmlspecialchars()
✅ Today's Deliverable
- ✓ Contact form that saves to text file
- ✓ Messages also saved to CSV format
- ✓ View messages page displaying all submissions
- ✓ Form validation working properly
- ✓ Success/error messages displaying
- ✓ Proper file handling (open/write/close)