Lecture Notes For Class 12
File Handling - Part 1
Objective:
- Learn basic file handling operations such as opening, reading, and writing files.
- Understand file upload processes.
Outcome:
- Students will be able to manage files by reading and writing data and handle file uploads via HTML forms.
Introduction to File Handling
File handling is a crucial part of programming that allows you to store, retrieve, and manipulate data in files on a computer. In this class, we will cover the basic operations of file handling in PHP, including how to open files, read from them, write to them, and upload files via HTML forms.
Why Use File Handling?
- Data Storage: Files provide a way to store data persistently.
- Data Retrieval: You can easily read data from files for processing.
- Data Manipulation: Files allow you to modify existing data and save changes.
Basic File Operations in PHP
In PHP, we can perform various file operations using built-in functions. The basic operations include:
- Opening a File
- Reading from a File
- Writing to a File
- Closing a File
1. Opening a File
To open a file in PHP, you use the fopen() function. This function takes two parameters: the filename and the mode in which you want to open the file.
File Modes:
- r: Read only (file must exist).
- w: Write only (creates a new file or truncates the existing file).
- a: Append (writes to the end of the file).
- x: Create and open for writing (fails if the file already exists).
- rb, wb, ab: The same as above but for binary files.
Example:
$file = fopen("example.txt", "w"); // Opens example.txt for writing
if ($file) {
echo "File opened successfully.";
} else {
echo "Error opening the file.";
}
2. Reading from a File
You can read data from a file using functions like fgets(), fread(), and file_get_contents().
Example Using fgets():
$file = fopen("example.txt", "r");
if ($file) {
while (($line = fgets($file)) !== false) {
echo $line; // Output each line
}
fclose($file); // Close the file after reading
} else {
echo "Error opening the file.";
}
3. Writing to a File
To write data to a file, you can use fwrite() or file_put_contents().
Example Using fwrite():
$file = fopen("example.txt", "w");
if ($file) {
fwrite($file, "Hello, World!\n"); // Write data to the file
fclose($file); // Close the file
} else {
echo "Error opening the file.";
}
4. Closing a File
After completing file operations, it is important to close the file using the fclose() function to free up system resources.
Example:
fclose($file); // Close the open file
File Upload Process in PHP
File uploads allow users to send files from their local systems to a web server. Here’s how to implement file uploads using HTML forms and PHP.
Step 1: Create an HTML Form
You need to create a form with the enctype attribute set to multipart/form-data.
Example:
<form action="upload.php" method="POST" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
Step 2: Handle File Upload in PHP
In the upload.php file, you can access the uploaded file using the $_FILES superglobal array.
Example:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$target_dir = "uploads/"; // Directory to save uploaded files
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
// Check if file is uploaded
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars(basename($_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
Key Points to Remember:
- Ensure the target directory (e.g., uploads/) exists and has the correct permissions.
- Use proper validation and error handling for file uploads (e.g., checking file type, size).
Conclusion
In this class, we covered the basic operations of file handling in PHP, including how to open, read, write, and close files. We also learned how to create a simple file upload form and handle file uploads using PHP.
Homework:
- Implement a program that reads data from a text file and writes the output to another file.
- Create a form that allows users to upload images and store them in a specified directory.