Assignments For Class 12
File Handling - Part 1
Assignment 1: File Reading and Writing
Objective: Implement file reading and writing operations.
- Create a PHP script that performs the following tasks:
- Open a text file named input.txt.
- Read the contents of the file line by line and display each line on the web page.
- Write the contents read from input.txt into a new file named output.txt.
- After writing, display a success message indicating that the content has been written to output.txt.
Instructions:
- Use fopen(), fgets(), fwrite(), and fclose() functions in your script.
- Ensure that you handle errors, such as when the file does not exist.
Assignment 2: File Upload Functionality
Objective: Create a file upload form and handle file uploads.
- Create an HTML form (named upload_form.html) that allows users to upload a file. Include:
- An input field of type file for the user to choose a file.
- A submit button to upload the file.
- Create a PHP script (named upload.php) that processes the file upload:
- Move the uploaded file to a directory called uploads/ on the server.
- Display a success message if the upload is successful or an error message if it fails.
- If the file upload is successful, display the name of the uploaded file.
Instructions:
- Ensure that the uploads/ directory exists and has the appropriate permissions.
- Validate the uploaded file type (e.g., allow only images or text files).
Assignment 3: Append Data to a File
Objective: Learn how to append data to an existing file.
- Create a PHP script that:
- Opens a text file named data.txt in append mode.
- Takes user input via a form (named append_form.html) to add a new line of text to the file.
- After submitting, append the new line to data.txt and display the entire contents of the file on the web page.
Instructions:
- Use the a mode in fopen() for appending data.
- Handle any potential errors during file operations.
Assignment 4: File Deletion
Objective: Implement file deletion functionality.
- Create a PHP script that:
- Displays a list of files in the uploads/ directory.
- Provides a delete button next to each file.
- When a user clicks the delete button, the corresponding file should be deleted from the server.
Instructions:
- Use the unlink() function to delete files.
- Ensure that you confirm the deletion action to avoid accidental deletions.
Assignment 5: File Upload with Validation
Objective: Enhance file upload functionality with validation.
- Modify the file upload functionality created in Assignment 2:
- Validate that the uploaded file is an image (e.g., JPG, PNG, GIF) or a text file.
- Check the file size (limit it to 2MB).
- If the file does not meet the criteria, display an appropriate error message.
Instructions:
- Use mime_content_type() or check the file extension for validation.
- Provide feedback to the user based on the validation results.
Submission Guidelines
- Submit your PHP files, HTML files, and any other relevant files as a zipped folder.
- Ensure your code is well-commented and organized for readability.
- Include a README file explaining your implementation and any challenges faced during the assignments.
SOLUTIONS
Assignment 1: File Reading and Writing
Solution Code (file_read_write.php):
<?php
// Open the input file for reading
$inputFile = fopen("input.txt", "r");
if (!$inputFile) {
die("Error opening input file.");
}
// Create (or overwrite) the output file for writing
$outputFile = fopen("output.txt", "w");
if (!$outputFile) {
die("Error opening output file.");
}
// Read from input file and write to output file
while (($line = fgets($inputFile)) !== false) {
echo htmlspecialchars($line) . "<br>"; // Display each line
fwrite($outputFile, $line); // Write to output file
}
// Close both files
fclose($inputFile);
fclose($outputFile);
echo "Content has been written to output.txt successfully.";
?>
Explanation:
- Opens input.txt for reading.
- Creates (or overwrites) output.txt for writing.
- Reads each line from input.txt and writes it to output.txt, while also displaying it on the web page.
- Closes both files and confirms success.
Assignment 2: File Upload Functionality
Solution Code (upload_form.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<form action="upload.php" method="POST" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload" required>
<input type="submit" value="Upload File" name="submit">
</form>
</body>
</html>
Solution Code (upload.php):
<?php
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 successfully
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.";
}
}
?>
Explanation:
- The HTML form (upload_form.html) allows users to select a file for upload.
- The PHP script (upload.php) processes the upload and moves the file to the uploads/ directory, displaying success or error messages.
Assignment 3: Append Data to a File
Solution Code (append_form.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Append Data</title>
</head>
<body>
<form action="append.php" method="POST">
Enter text to append:
<input type="text" name="appendText" required>
<input type="submit" value="Append">
</form>
</body>
</html>
Solution Code (append.php):
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$textToAppend = $_POST['appendText'];
$file = fopen("data.txt", "a");
if (!$file) {
die("Error opening file.");
}
// Write the new line to the file
fwrite($file, $textToAppend . "\n");
fclose($file);
// Display the entire contents of data.txt
echo "<h3>Contents of data.txt:</h3>";
$file = fopen("data.txt", "r");
while (($line = fgets($file)) !== false) {
echo htmlspecialchars($line) . "<br>"; // Display each line
}
fclose($file);
}
?>
Explanation:
- The HTML form (append_form.html) allows users to input text to append.
- The PHP script (append.php) appends the text to data.txt and displays its entire contents.
Assignment 4: File Deletion
Solution Code (delete_files.php):
<?php
$directory = 'uploads/';
$files = scandir($directory);
foreach ($files as $file) {
if ($file !== '.' && $file !== '..') {
echo htmlspecialchars($file) . " ";
echo "<form action='' method='POST' style='display:inline;'>
<input type='hidden' name='filename' value='" . htmlspecialchars($file) . "'>
<input type='submit' value='Delete'>
</form><br>";
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['filename'])) {
$fileToDelete = $directory . $_POST['filename'];
if (unlink($fileToDelete)) {
echo "File " . htmlspecialchars($_POST['filename']) . " has been deleted.";
} else {
echo "Error deleting file.";
}
}
?>
Explanation:
- This script lists files in the uploads/ directory and provides a delete button for each.
- Upon clicking the delete button, the selected file is deleted using unlink(), and a confirmation message is displayed.
Assignment 5: File Upload with Validation
Solution Code (upload_with_validation.php):
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
// Get file type and size
$fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$fileSize = $_FILES["fileToUpload"]["size"];
// Validate file type
if ($fileType != "jpg" && $fileType != "png" && $fileType != "gif" && $fileType != "txt") {
echo "Sorry, only JPG, PNG, GIF, and TXT files are allowed.";
$uploadOk = 0;
}
// Validate file size
if ($fileSize > 2097152) { // Limit size to 2MB
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Check if everything is ok to upload
if ($uploadOk == 1) {
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.";
}
}
}
?>
Explanation:
- This PHP script validates the uploaded file's type (allowing only specific formats) and size (max 2MB).
- If validation passes, the file is uploaded to the uploads/ directory; otherwise, an appropriate error message is displayed.
Assignment 6: File Existence Check
Objective: Learn how to check if a file exists before performing operations.
- Create a PHP script that:
- Checks if a file named example.txt exists.
- If it exists, read and display its contents.
- If it does not exist, create the file and write a message "This is a new file." to it.
Solution Code (file_existence.php):
<?php
$filename = "example.txt";
if (file_exists($filename)) {
echo "File exists. Reading contents:<br>";
$file = fopen($filename, "r");
while (($line = fgets($file)) !== false) {
echo htmlspecialchars($line) . "<br>"; // Display each line
}
fclose($file);
} else {
// Create the file and write to it
$file = fopen($filename, "w");
fwrite($file, "This is a new file.");
fclose($file);
echo "File did not exist. Created new file: $filename";
}
?>
Explanation:
- The script checks for the existence of example.txt using file_exists().
- If the file exists, it opens it for reading and displays its contents.
- If the file does not exist, it creates the file and writes a default message into it.
Assignment 7: Reading a CSV File
Objective: Understand how to read data from a CSV file.
- Create a CSV file named data.csv with the following content:
Name, Age, Email
John Doe, 30, john@example.com
Jane Smith, 25, jane@example.com
- Create a PHP script that reads the CSV file and displays its contents in an HTML table.
Solution Code (read_csv.php):
<?php
$filename = "data.csv";
echo "<table border='1'>";
echo "<tr><th>Name</th><th>Age</th><th>Email</th></tr>";
if (($handle = fopen($filename, "r")) !== false) {
// Read each line of the CSV file
while (($data = fgetcsv($handle)) !== false) {
echo "<tr>";
foreach ($data as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>";
}
fclose($handle);
}
echo "</table>";
} else {
echo "File not found.";
}
?>
Explanation:
- The script checks for the existence of data.csv.
- If the file exists, it opens the file for reading using fgetcsv(), which reads each line as an array.
- The data is displayed in an HTML table format.
Assignment 8: File Copying
Objective: Learn how to copy a file from one location to another.
- Create a PHP script that:
- Copies example.txt to a new file named example_copy.txt.
- Check if the copy operation is successful and display a corresponding message.
Solution Code (copy_file.php):
<?php
$sourceFile = "example.txt";
$destinationFile = "example_copy.txt";
if (copy($sourceFile, $destinationFile)) {
echo "File copied successfully to $destinationFile.";
} else {
echo "Failed to copy file.";
}
?>
Explanation:
- The script uses the copy() function to copy example.txt to example_copy.txt.
- It checks if the copy operation was successful and displays an appropriate message.
Assignment 9: Writing Multiple Lines to a File
Objective: Write multiple lines of text to a file.
- Create a PHP script that:
- Takes an array of strings.
- Writes each string as a new line in a file named multilines.txt.
Solution Code (write_multilines.php):
<?php
$lines = [
"First line of text.",
"Second line of text.",
"Third line of text."
];
$filename = "multilines.txt";
$file = fopen($filename, "w");
if (!$file) {
die("Error opening file.");
}
foreach ($lines as $line) {
fwrite($file, $line . PHP_EOL); // PHP_EOL ensures a new line
}
echo "Lines have been written to $filename successfully.";
?>
Explanation:
- The script initializes an array of strings and opens multilines.txt for writing.
- It loops through the array and writes each string to the file, adding a newline character after each line.
- Closes the file and confirms success.
Assignment 10: File Upload with Error Handling
Objective: Enhance file upload functionality with more detailed error handling.
- Modify the file upload script (from Assignment 2) to:
- Check for file upload errors (e.g., file too large, no file selected).
- Provide detailed error messages based on the error code.
Solution Code (upload_with_error_handling.php):
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
// Check if file was uploaded without errors
if ($_FILES["fileToUpload"]["error"] !== UPLOAD_ERR_OK) {
switch ($_FILES["fileToUpload"]["error"]) {
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
echo "Error: Your file is too large.";
$uploadOk = 0;
break;
case UPLOAD_ERR_NO_FILE:
echo "Error: No file was uploaded.";
$uploadOk = 0;
break;
default:
echo "Error: An unknown error occurred.";
$uploadOk = 0;
break;
}
}
// Proceed with upload if no errors
if ($uploadOk === 1) {
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.";
}
}
}
?>
Explanation:
- The script checks for file upload errors using $_FILES["fileToUpload"]["error"].
- It provides specific error messages based on the error code, improving user feedback during the upload process.