Assignments Of Class 31 - Advanced File Handling in PHP
Here are some assignments on advanced file handling in PHP, along with solutions for each assignment. These assignments will help students practice the concepts covered in the lecture.
Assignment 1: Word Count in a Large Text File
Objective: Create a PHP script that reads a large text file and counts the number of words.
Requirements:
1. The script should prompt the user to enter the file path of the text file.
2. It should read the file line by line.
3. Count and display the total number of words in the file.
Solution:
php
Copy code
<?php
function countWordsInFile($filePath) {
$wordCount = 0;
// Check if file exists
if (!file_exists($filePath)) {
echo "Error: The file does not exist.";
return;
}
// Open the file
$handle = fopen($filePath, 'r');
if ($handle) {
// Read the file line by line
while (($line = fgets($handle)) !== false) {
// Count words in the line
$wordCount += str_word_count($line);
}
fclose($handle);
} else {
echo "Error opening the file.";
}
echo "Total number of words in the file: " . $wordCount;
}
// Usage
echo "Enter the file path: ";
$filePath = trim(fgets(STDIN));
countWordsInFile($filePath);
?>
Assignment 2: CSV to Associative Array
Objective: Write a PHP function that reads a CSV file and converts it into an associative array.
Requirements:
1. The first row of the CSV file contains the headers.
2. Each subsequent row should be converted into an associative array with the headers as keys.
Solution:
php
Copy code
<?php
function csvToAssociativeArray($filePath) {
$data = [];
// Check if file exists
if (!file_exists($filePath)) {
echo "Error: The file does not exist.";
return;
}
// Open the CSV file
$handle = fopen($filePath, 'r');
if ($handle) {
// Get the headers
$headers = fgetcsv($handle);
// Read each row and map to associative array
while (($row = fgetcsv($handle)) !== false) {
$data[] = array_combine($headers, $row);
}
fclose($handle);
} else {
echo "Error opening the file.";
}
return $data;
}
// Usage
$filePath = 'data.csv'; // Change this to your CSV file path
$dataArray = csvToAssociativeArray($filePath);
print_r($dataArray);
?>
Assignment 3: File Upload with Stream Handling
Objective: Create a PHP script that allows users to upload large files using streams.
Requirements:
1. The script should handle file uploads and save them to a specified directory.
2. It should check for errors and file size limits.
Solution:
php
Copy code
<?php
$targetDir = "uploads/";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$file = $_FILES['fileToUpload'];
// Check if file was uploaded without errors
if (isset($file) && $file['error'] === UPLOAD_ERR_OK) {
$targetFilePath = $targetDir . basename($file["name"]);
// Check file size (limit to 5MB)
if ($file["size"] > 5000000) {
echo "Error: File is too large.";
exit;
}
// Move the uploaded file to the target directory
if (move_uploaded_file($file["tmp_name"], $targetFilePath)) {
echo "The file " . htmlspecialchars(basename($file["name"])) . " has been uploaded.";
} else {
echo "Error uploading the file.";
}
} else {
echo "Error: " . $file['error'];
}
}
?>
<!-- HTML form for file upload -->
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" required>
<input type="submit" value="Upload File">
</form>
</body>
</html>
Assignment 4: Read and Display a Large File in Chunks
Objective: Write a PHP script that reads a large file in chunks and displays its content.
Requirements:
1. The script should read a specified number of bytes at a time and display them.
2. The user should be able to navigate through the file using "Next" and "Previous" buttons.
Solution:
php
Copy code
<?php
session_start();
$filename = 'largefile.txt'; // Change this to your file path
$chunkSize = 1024; // Number of bytes to read at a time
if (!file_exists($filename)) {
echo "Error: The file does not exist.";
exit;
}
$handle = fopen($filename, 'r');
if (!$handle) {
echo "Error opening the file.";
exit;
}
// Initialize session variables to track the current position
if (!isset($_SESSION['position'])) {
$_SESSION['position'] = 0;
}
// Handle "Next" and "Previous" requests
if (isset($_POST['next'])) {
$_SESSION['position'] += $chunkSize;
} elseif (isset($_POST['previous'])) {
$_SESSION['position'] = max(0, $_SESSION['position'] - $chunkSize);
}
// Seek to the current position
fseek($handle, $_SESSION['position']);
// Read the chunk
$content = fread($handle, $chunkSize);
fclose($handle);
// Display the content
echo nl2br(htmlspecialchars($content));
// Navigation buttons
echo '<form method="post">';
if ($_SESSION['position'] > 0) {
echo '<input type="submit" name="previous" value="Previous">';
}
if (strlen($content) === $chunkSize) {
echo '<input type="submit" name="next" value="Next">';
}
echo '</form>';
?>
Summary
These assignments encourage students to practice file handling in PHP by working with large files, converting CSV data into associative arrays, uploading files using streams, and displaying file content in manageable chunks. Each solution demonstrates best practices in file handling, including error checking and efficient data processing.