Assignments For Class 13: File Handling - Part 2
Here are some assignments related to File Handling - Part 2, complete with solutions and detailed explanations. These assignments will help reinforce the concepts covered in the class.
Assignment 1: Create a Directory Structure
Objective: Create a PHP script that generates a directory structure for a project. The structure should include folders for images, documents, and backups.
Instructions:
- Write a PHP script that checks if each folder already exists before creating it.
- Output messages indicating whether each folder was created or if it already existed.
Solution:
php
Copy code
<?php
// Define the directory names
$directories = ['images', 'documents', 'backups'];
// Loop through the directory names
foreach ($directories as $dir) {
// Check if the directory exists
if (!is_dir($dir)) {
// Create the directory
mkdir($dir, 0777);
echo "Directory '$dir' created successfully!<br>";
} else {
echo "Directory '$dir' already exists.<br>";
}
}
?>
Explanation:
- The script defines an array of directory names.
- It iterates through this array, checking if each directory exists using is_dir().
- If the directory does not exist, it creates it with mkdir(), specifying permissions.
- It outputs a success message for each created directory or a message indicating that the directory already exists.
Assignment 2: List Files in a Directory
Objective: Write a PHP script that lists all files in a specified directory and outputs their names along with their sizes.
Instructions:
- Use the scandir() function to get all files in the directory.
- For each file, use filesize() to determine its size.
- Output the file names and sizes.
Solution:
php
Copy code
<?php
// Specify the directory
$dir = "."; // Current directory
// Get all files and directories
$files = scandir($dir);
// Output file names and sizes
echo "Files in '$dir':<br>";
foreach ($files as $file) {
if ($file != "." && $file != ".." && is_file($file)) { // Check if it's a file
$size = filesize($file); // Get file size
echo "$file - " . $size . " bytes<br>";
}
}
?>
Explanation:
- The script sets the target directory as the current directory (".").
- It retrieves all items in the directory using scandir().
- It iterates through the items, checking if each one is a file (skipping . and ..).
- For each file, it uses filesize() to get its size and outputs the file name with its corresponding size.
Assignment 3: Delete a Directory
Objective: Create a PHP script that deletes a specified directory if it is empty. If the directory is not empty, output a message indicating that it cannot be deleted.
Instructions:
- Check if the directory is empty using scandir().
- If it’s empty, delete it using rmdir().
- If not, display a message.
Solution:
php
Copy code
<?php
// Specify the directory to delete
$dir = "empty_folder"; // Change this to the folder you want to delete
// Check if the directory exists
if (is_dir($dir)) {
$files = scandir($dir);
// Check if the directory is empty
if (count($files) == 2) { // Only '.' and '..' present
rmdir($dir);
echo "Directory '$dir' deleted successfully!";
} else {
echo "Directory '$dir' is not empty and cannot be deleted.";
}
} else {
echo "Directory '$dir' does not exist.";
}
?>
Explanation:
- The script specifies a directory to delete.
- It checks if the directory exists using is_dir().
- It retrieves the contents of the directory with scandir() and counts the files.
- If there are only two items (the . and ..), it calls rmdir() to delete the directory and outputs a success message.
- If there are additional files, it outputs a message indicating the directory cannot be deleted.
Assignment 4: Organizing Files by Extension
Objective: Write a PHP script that organizes files in a specified directory into subdirectories based on their file extensions (e.g., .txt, .jpg, .pdf).
Instructions:
- Use scandir() to retrieve all files in the specified directory.
- For each file, determine its extension using pathinfo().
- Create a subdirectory for each unique extension and move the file into the corresponding subdirectory.
Solution:
php
Copy code
<?php
// Specify the source directory
$sourceDir = "."; // Current directory
// Get all files and directories
$files = scandir($sourceDir);
// Loop through files
foreach ($files as $file) {
if ($file != "." && $file != ".." && is_file($file)) { // Check if it's a file
$extension = pathinfo($file, PATHINFO_EXTENSION); // Get file extension
$targetDir = $sourceDir . "/" . $extension; // Create target directory path
// Check if the target directory exists, if not, create it
if (!is_dir($targetDir)) {
mkdir($targetDir, 0777);
}
// Move the file to the target directory
rename($file, $targetDir . "/" . $file);
echo "Moved '$file' to '$targetDir'<br>";
}
}
?>
Explanation:
- The script sets the source directory to the current directory.
- It retrieves all items using scandir().
- For each file, it checks if it’s a valid file (not . or ..).
- It uses pathinfo() to get the file extension.
- It constructs the path for the target directory based on the extension.
- If the target directory does not exist, it creates it.
- Finally, it uses rename() to move the file into the respective subdirectory.
Assignment 5: Display Current Working Directory and Change It
Objective: Write a PHP script that displays the current working directory and then changes it to a specified directory.
Instructions:
- Use getcwd() to get the current directory.
- Use chdir() to change to a specified directory.
- Display the new working directory.
Solution:
php
Copy code
<?php
// Display the current working directory
$currentDir = getcwd();
echo "Current Directory: " . $currentDir . "<br>";
// Specify the new directory
$newDir = "new_folder"; // Change this to the folder you want to switch to
// Change the current working directory
if (is_dir($newDir)) {
chdir($newDir);
echo "Changed Directory to: " . getcwd();
} else {
echo "Directory '$newDir' does not exist.";
}
?>
Explanation:
- The script retrieves the current working directory using getcwd() and displays it.
- It checks if the specified new directory exists using is_dir().
- If it exists, it changes the working directory with chdir() and displays the new current working directory.
- If it does not exist, it outputs a message indicating that the directory does not exist.
Summary of Assignments
These assignments cover various aspects of file handling, including creating directories, listing files, deleting directories, organizing files by extension, and managing the current working directory. They help reinforce the concepts taught in class and provide practical applications for file handling in PHP. Encourage students to experiment with these scripts, modify them, and explore further functionalities as they become more comfortable with file operations.
4o mini
You said:
give some more
ChatGPT said:
ChatGPT
Here are additional assignments related to File Handling - Part 2, complete with solutions and explanations. These assignments are designed to further reinforce students' understanding of advanced file handling techniques in PHP.
Assignment 6: Copying Files
Objective: Create a PHP script that copies a specified file from one directory to another.
Instructions:
- Use the copy() function to copy a file.
- Check if the source file exists and if the destination directory is writable.
- Output appropriate messages for success or failure.
Solution:
php
Copy code
<?php
// Specify the source file and destination directory
$sourceFile = "source.txt"; // Change to the file you want to copy
$destinationDir = "backup"; // Change to your destination directory
// Check if the source file exists
if (file_exists($sourceFile)) {
// Check if the destination directory is writable
if (is_writable($destinationDir)) {
// Construct the destination file path
$destinationFile = $destinationDir . "/" . basename($sourceFile);
// Copy the file
if (copy($sourceFile, $destinationFile)) {
echo "File '$sourceFile' copied to '$destinationFile' successfully!";
} else {
echo "Failed to copy '$sourceFile' to '$destinationFile'.";
}
} else {
echo "Destination directory '$destinationDir' is not writable.";
}
} else {
echo "Source file '$sourceFile' does not exist.";
}
?>
Explanation:
- The script sets the source file and destination directory.
- It checks if the source file exists using file_exists().
- It checks if the destination directory is writable using is_writable().
- If both checks pass, it constructs the destination file path and uses copy() to copy the file.
- It outputs success or failure messages based on the results.
Assignment 7: File Read and Write
Objective: Write a PHP script that reads the contents of a file and writes new content to it.
Instructions:
- Open a file for reading and display its contents.
- Append new content to the file.
- Display the updated contents of the file.
Solution:
php
Copy code
<?php
// Specify the file to read and write
$file = "example.txt"; // Change to your file
// Read the contents of the file
if (file_exists($file)) {
$contents = file_get_contents($file);
echo "Original Contents:<br>$contents<br>";
// New content to append
$newContent = "This is the new content being added.\n";
// Append new content to the file
file_put_contents($file, $newContent, FILE_APPEND);
echo "New content appended successfully!<br>";
// Display updated contents
$updatedContents = file_get_contents($file);
echo "Updated Contents:<br>$updatedContents";
} else {
echo "File '$file' does not exist.";
}
?>
Explanation:
- The script specifies the file to read and write.
- It checks if the file exists, then reads its contents using file_get_contents().
- It outputs the original contents.
- It appends new content using file_put_contents() with the FILE_APPEND flag.
- Finally, it reads and displays the updated contents of the file.
Assignment 8: Search for a Word in a File
Objective: Create a PHP script that searches for a specific word in a text file and counts its occurrences.
Instructions:
- Read the contents of the file into a string.
- Use substr_count() to count the occurrences of the specified word.
- Output the count.
Solution:
php
Copy code
<?php
// Specify the file and word to search for
$file = "example.txt"; // Change to your file
$searchWord = "new"; // Change to the word you want to search for
// Check if the file exists
if (file_exists($file)) {
// Read the file contents
$contents = file_get_contents($file);
// Count occurrences of the search word
$count = substr_count($contents, $searchWord);
// Output the result
echo "The word '$searchWord' occurs $count time(s) in the file '$file'.";
} else {
echo "File '$file' does not exist.";
}
?>
Explanation:
- The script sets the file and the word to search for.
- It checks if the file exists, then reads its contents.
- It uses substr_count() to count the occurrences of the specified word in the file contents.
- It outputs the number of occurrences.
Assignment 9: Moving Files Between Directories
Objective: Write a PHP script that moves a specified file from one directory to another.
Instructions:
- Use the rename() function to move a file.
- Check if the source file exists and if the destination directory is writable.
- Output appropriate messages for success or failure.
Solution:
php
Copy code
<?php
// Specify the source file and destination directory
$sourceFile = "example.txt"; // Change to your source file
$destinationDir = "new_folder"; // Change to your destination directory
// Check if the source file exists
if (file_exists($sourceFile)) {
// Check if the destination directory is writable
if (is_writable($destinationDir)) {
// Construct the new file path
$destinationFile = $destinationDir . "/" . basename($sourceFile);
// Move the file
if (rename($sourceFile, $destinationFile)) {
echo "File '$sourceFile' moved to '$destinationFile' successfully!";
} else {
echo "Failed to move '$sourceFile' to '$destinationFile'.";
}
} else {
echo "Destination directory '$destinationDir' is not writable.";
}
} else {
echo "Source file '$sourceFile' does not exist.";
}
?>
Explanation:
- The script specifies the source file and destination directory.
- It checks if the source file exists using file_exists().
- It checks if the destination directory is writable using is_writable().
- If both checks pass, it constructs the destination file path and uses rename() to move the file.
- It outputs success or failure messages based on the results.
Assignment 10: File Permissions
Objective: Create a PHP script that changes the permissions of a specified file and displays its current permissions.
Instructions:
- Use fileperms() to get the current permissions of a file.
- Use chmod() to change the permissions of the file.
- Output the current and new permissions.
Solution:
php
Copy code
<?php
// Specify the file
$file = "example.txt"; // Change to your file
// Check if the file exists
if (file_exists($file)) {
// Get current permissions
$currentPerms = fileperms($file);
echo "Current Permissions: " . sprintf('%o', $currentPerms) . "<br>";
// Change permissions
chmod($file, 0644); // Set permissions to read/write for owner, read for group and others
echo "Permissions changed successfully!<br>";
// Get new permissions
$newPerms = fileperms($file);
echo "New Permissions: " . sprintf('%o', $newPerms);
} else {
echo "File '$file' does not exist.";
}
?>
Explanation:
- The script specifies the file for which to check and change permissions.
- It checks if the file exists and retrieves its current permissions using fileperms().
- It outputs the current permissions.
- It changes the file permissions using chmod(), setting it to read/write for the owner and read-only for others.
- It retrieves and displays the new permissions.
Summary of Additional Assignments
These additional assignments cover a range of file handling tasks, including copying, reading, writing, searching, moving files, and managing file permissions. Each assignment provides students with practical experience in handling files and directories using PHP. Encourage students to test these scripts in different scenarios and modify them to explore additional functionalities.
4o mini
You said:
write 100 mcq from same above topic
ChatGPT said:
ChatGPT
Here are 100 multiple-choice questions (MCQs) focused on File Handling - Part 2 in PHP, designed to assess students' understanding of advanced file handling techniques, including directory operations and file management.