0% found this document useful (0 votes)
10 views6 pages

Chapter 7

Chapter 7 of 'Internet Programming II' covers file handling in web applications, emphasizing its importance for data persistence, logging, configuration management, and content management. It details PHP functions for reading and writing files, handling errors, and managing file permissions, along with practical examples for logging user visits and managing directories. Additionally, it introduces image processing using the GD Library for tasks like resizing, cropping, and adding watermarks to images.

Uploaded by

agetachew97
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views6 pages

Chapter 7

Chapter 7 of 'Internet Programming II' covers file handling in web applications, emphasizing its importance for data persistence, logging, configuration management, and content management. It details PHP functions for reading and writing files, handling errors, and managing file permissions, along with practical examples for logging user visits and managing directories. Additionally, it introduces image processing using the GD Library for tasks like resizing, cropping, and adding watermarks to images.

Uploaded by

agetachew97
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Internet Programming II - 2017EC

Chapter 7
File Handling
7.1 Introduction to File Handling
File handling allows web applications to interact with files on the server. This is essential for tasks like
storing user data, logging events, and managing configuration settings. Without file handling, web
applications would rely solely on databases, which might not be practical for all types of data storage.

Key reasons for file handling include:

 Data persistence, where files store information like user preferences between sessions
 Logging, which helps web applications track user actions, errors, and events for debugging and
monitoring
 Configuration management, where settings are saved in files for flexibility and easy customization
 Content management, enabling websites with dynamic content, such as blogs or news sites, to store
and serve content efficiently

Examples of file handling in web development include access logs, where web servers like Apache or Nginx
store logs of each request made to the server. Error logs, where applications log errors to a file for easier
debugging. User uploads, where platforms like social media sites handle file uploads (images, documents)
and store them on the server. Configuration files, where web apps often use JSON, XML, or PHP files to
control behavior without changing the code. Data backups, where periodic backups of database exports
or critical data files ensure recovery from data loss.

7.1. Reading & Writing Files


File Handling Overview

PHP provides various functions to handle files efficiently. Some key functions include the following:

Opening a File

The fopen() function is used to open files. It requires two main arguments: the file name and the mode.

Example:

$file = fopen("visits.log", "a+");


Common modes include:

1 of 6
Internet Programming II - 2017EC

Mode Description
r Read-only. Starts at the beginning of the file.
r+ Read and write. Starts at the beginning of the file.
w Write-only. Erases the content or creates a new file.
w+ Read and write. Erases the content or creates a new file.
a Write-only. Appends data to the end of the file. Creates a new file if it doesn’t exist.
a+ Read and append. Starts at the end of the file. Creates a new file if it doesn’t exist.
x Write-only. Creates a new file. Returns FALSE if the file already exists.
x+ Read and write. Creates a new file. Returns FALSE if the file already exists.
c Write-only. Opens the file but does not create it if it doesn’t exist. Doesn’t overwrite content.
c+ Read and write. Similar to c, but allows reading too.

Reading from Files

fread() reads a specific number of bytes from a file:


$file = fopen("example.txt", "r");
$content = fread($file, filesize("example.txt"));
fclose($file);
file_get_contents() reads the entire file into a string (simpler for small files):
$content = file_get_contents("example.txt");
echo $content;

fgets() Reads the file line-by-line (until newline \n), useful for processing large files without loading
the entire content

$handle = fopen("file.txt", "r");


while (($line = fgets($handle)) !== false) {
echo $line . "<br>";
}
fclose($handle);
fgetc() reads one character at a time, useful for fine-grained parsing or tokenization.

$handle = fopen("file.txt", "r");


while (($char = fgetc($handle)) !== false) {
echo $char;
}
fclose($handle);
feof() checks if the end of file has been reached, used in loops to avoid errors when reading past file

end.

2 of 6
Internet Programming II - 2017EC

$handle = fopen("file.txt", "r");


while (!feof($handle)) {
echo fgets($handle);
}
fclose($handle);

Writing to Files

fwrite() writes data to an open file:


$file = fopen("log.txt", "a");
fwrite($file, "User visited on " . date("Y-m-d H:i:s") . "\n");
fclose($file);
Handling Errors

It’s essential to handle errors, like when a file doesn’t exist or lacks permissions.

Example:

$file = @fopen("nonexistent.txt", "r") or die("Error: File not found!");


The @ suppresses errors, while die() outputs a custom error message.

File Permissions and Security Considerations

 Permissions: Ensure proper permissions (e.g., chmod 644) to prevent unauthorized access.
 Security: Avoid reading/writing sensitive files like /etc/passwd. Always validate file paths.

Simple Log System (build a basic log system to track user visits)

// Open or create the log file


$logFile = fopen("visits.log", "a") or die("Unable to open file!");

// Record the visit with timestamp and IP address


$logEntry = "Visit from IP: " . $_SERVER['REMOTE_ADDR'] . " on " . date("Y-
m-d H:i:s") . "\n";

// Write the entry to the log


fwrite($logFile, $logEntry);

// Close the file


fclose($logFile);

3 of 6
Internet Programming II - 2017EC

echo "Visit logged successfully!";


This script opens the visits.log file in append mode, ensuring that new entries are added without
overwriting existing data. It captures the user's IP address along with the current timestamp, creating a
record of the visit. The log entry is then written to the file, and the script ensures the file is properly closed
to prevent data loss or corruption.

7.2. File and Directory Control


PHP provides functions to work with files and folders, allowing developers to automate tasks such as
uploading files, organizing data, and managing user content.

Deleting Files

unlink(filename) deletes a specified file from the file system.

$profilePic = "uploads/user123.jpg";
if (file_exists($profilePic)) {
unlink($profilePic);
echo "Profile picture deleted.";
} else {
echo "File not found.";
}
Creating Directories

mkdir(path, mode, recursive) creates a new directory.

$username = "user123";
$userFolder = "uploads/$username";
if (!is_dir($userFolder)) {
mkdir($userFolder, 0755, true);
echo "User folder created.";
} else {
echo "Folder already exists.";
}

0755 is the permission setting, and true allows nested folders if needed.

4 of 6
Internet Programming II - 2017EC

Removing Directories

rmdir(directory) removes an empty directory

$categoryFolder = "uploads/category-abc";

if (is_dir($categoryFolder) && count(scandir($categoryFolder)) == 2) {


// Only '.' and '..' exist
rmdir($categoryFolder);
echo "Empty category folder removed.";
} else {
echo "Folder is not empty or doesn't exist.";
}
Understanding Paths

Working with correct file paths is key to file operations.

a. Server Root Directory:

$_SERVER['DOCUMENT_ROOT']gives the root directory of the server where the current script is running.

$uploadPath = $_SERVER['DOCUMENT_ROOT'] . "/uploads/file.txt";


file_put_contents($uploadPath, "Hello world!");
echo "File saved to: $uploadPath";
b. Current Script Directory

__DIR__ returns the directory of the currently executing script.

include(__DIR__ . "/config.php");

Prevents errors when scripts are executed from different locations.

7.3. Image Processing


The GD Library is a powerful tool in PHP for creating and manipulating images. It supports various image
formats like JPEG, PNG, GIF, and WebP. With GD, you can create images from scratch, modify existing
ones, and perform tasks like resizing, cropping, and adding watermarks.

Resizing Images

function resizeImage($file, $width, $height) {


list($origWidth, $origHeight) = getimagesize($file);
$imageResized = imagecreatetruecolor($width, $height);

5 of 6
Internet Programming II - 2017EC

$image = imagecreatefromjpeg($file);

imagecopyresampled($imageResized, $image, 0, 0, 0, 0, $width, $height,


$origWidth, $origHeight);
imagejpeg($imageResized, 'resized_image.jpg');
}
Cropping Images

function cropImage($file, $x, $y, $cropWidth, $cropHeight) {


$image = imagecreatefromjpeg($file);
$imageCropped = imagecreatetruecolor($cropWidth, $cropHeight);

imagecopyresampled($imageCropped, $image, 0, 0, $x, $y, $cropWidth,


$cropHeight, $cropWidth, $cropHeight);
imagejpeg($imageCropped, 'cropped_image.jpg');
}
Adding Watermarks

function addWatermark($file, $text) {


$image = imagecreatefromjpeg($file);
$color = imagecolorallocate($image, 255, 255, 255);
$font = __DIR__ . '/arial.ttf';

imagettftext($image, 20, 0, 10, 30, $color, $font, $text);


imagejpeg($image, 'watermarked_image.jpg');
}

6 of 6

You might also like