Current Affairs updated daily
KalviGavaniKalviGavani
Class 12 · Tamil Nadu State Board

Forms and Files Exercise Solutions | KalviGavani

Samacheer Kalvi Class 12 Computer Applications Chapter 8 Forms and Files exercise solutions — HTML forms, PHP form handling with $_GET, $_POST, $_REQUEST, form validation, file handling (fopen, fwrite, fread, fclose), and file upload with worked examples.

Updated 13 June 202614 min read

Chapter 8 — Forms and Files: Exercise Solutions Guide

How to Use This Page

1. Attempt every exercise on your own before reading the solutions. 2. Compare your method with the answer shown — focus on the logic, not just the final output. 3. Practise writing HTML forms and PHP file-handling code by hand; the exam often asks you to write complete programs.


Key Concepts (Quick Recap)

  • An HTML form collects user input using elements like <input>, <textarea>, <select>, <radio>, and <checkbox>.
  • The <form> tag uses action (URL to send data to) and method (GET or POST) attributes.
  • $_GET — collects data sent via URL query string; visible in address bar, limited to ~2048 characters.
  • $_POST — collects data sent in HTTP body; invisible in address bar, no size limit, more secure.
  • $_REQUEST — contains data from both $_GET, $_POST, and $_COOKIES; convenient but less secure.
  • Form validation checks user input before processing — can be client-side (JavaScript) or server-side (PHP).
  • File handling in PHP uses functions: fopen(), fwrite(), fread(), fclose(), file_get_contents(), file_put_contents().
  • fopen() modes: r (read), w (write, truncate), a (append), r+, w+, a+.
  • File upload requires enctype="multipart/form-data" in the form tag and uses the $_FILES superglobal.
  • Always validate and sanitize form data on the server side before using it.
  • Use htmlspecialchars() to prevent XSS attacks when displaying user input.

I. Choose the Best Answer (MCQs)

1. Which superglobal array is used to collect form data sent with method="GET"?
Answer

(a) $_POST &nbsp;&nbsp; (b) $_REQUEST &nbsp;&nbsp; (c) $_GET &nbsp;&nbsp; (d) $_FILES

Answer(c) $_GET

Explanation: The $_GET superglobal collects values sent via the URL query string when the form method is GET.


2. Which form attribute is required for file uploads?
Answer

(a) method="POST" &nbsp;&nbsp; (b) action="upload.php" &nbsp;&nbsp; (c) enctype="multipart/form-data" &nbsp;&nbsp; (d) type="file"

Answer(c) enctype="multipart/form-data"

Explanation: Without enctype="multipart/form-data", the browser will not send the file content. The form method must also be POST for file uploads.


3. What does fopen("data.txt", "w") do?
Answer

(a) Opens the file for reading &nbsp;&nbsp; (b) Opens the file for writing, creating it if it doesn't exist and truncating if it does &nbsp;&nbsp; (c) Opens the file for appending &nbsp;&nbsp; (d) Opens the file for reading and writing

Answer(b) Opens the file for writing, creating it if it doesn't exist and truncating if it does

Explanation: Mode w opens for writing only; it creates the file if it doesn't exist and erases all existing content (truncates) if it does.


4. Which function is used to read a specified number of bytes from a file?
Answer

(a) fgets() &nbsp;&nbsp; (b) fread() &nbsp;&nbsp; (c) file() &nbsp;&nbsp; (d) readfile()

Answer(b) fread()

Explanation: fread($handle, $length) reads up to $length bytes from the file pointer. fgets() reads one line.


5. Which of the following is an advantage of POST over GET?
Answer

(a) Data is cached by the browser &nbsp;&nbsp; (b) Data appears in the URL &nbsp;&nbsp; (c) Data is sent in the HTTP body, making it more secure &nbsp;&nbsp; (d) Data has a 2048-character limit

Answer(c) Data is sent in the HTTP body, making it more secure

Explanation: POST sends data in the request body (invisible in URL), has no practical size limit, and is preferred for sensitive data like passwords.


6. What does $_FILES['file']['tmp_name'] contain?
Answer

(a) Original file name &nbsp;&nbsp; (b) MIME type &nbsp;&nbsp; (c) Temporary filename on the server &nbsp;&nbsp; (d) File size

Answer(c) Temporary filename on the server

Explanation: When a file is uploaded, PHP stores it in a temporary location. tmp_name gives that temporary path, which you use with move_uploaded_file().


7. Which function writes a string to a file?
Answer

(a) fread() &nbsp;&nbsp; (b) fwrite() &nbsp;&nbsp; (c) fopen() &nbsp;&nbsp; (d) fclose()

Answer(b) fwrite()

Explanation: fwrite($handle, $string) writes the contents of $string to the file pointed to by $handle.


8. What does the htmlspecialchars() function do?
Answer

(a) Encrypts data &nbsp;&nbsp; (b) Converts special characters to HTML entities to prevent XSS &nbsp;&nbsp; (c) Validates email format &nbsp;&nbsp; (d) Strips HTML tags entirely

Answer(b) Converts special characters to HTML entities to prevent XSS

Explanation: It converts characters like <, >, ", & into &lt;, &gt;, &quot;, &amp; so they render as text rather than being interpreted as HTML.


9. In PHP, which mode opens a file for reading and writing without truncating it?
Answer

(a) w &nbsp;&nbsp; (b) a &nbsp;&nbsp; (c) r+ &nbsp;&nbsp; (d) w+

Answer(c) r+

Explanation: r+ opens for both reading and writing, placing the pointer at the beginning, without truncating. w+ truncates the file; a only appends.


10. Which function moves an uploaded file to a permanent location?
Answer

(a) copy() &nbsp;&nbsp; (b) fopen() &nbsp;&nbsp; (c) move_uploaded_file() &nbsp;&nbsp; (d) rename()

Answer(c) move_uploaded_file()

Explanation: move_uploaded_file($tmp_name, $destination) is the secure way to move an uploaded file from its temporary location to a permanent path.


II. Fill in the Blanks

1. The <form> tag uses the action attribute to specify the URL where form data is sent.

2. The method attribute of <form> can be either GET or POST.

3. The superglobal $_POST is used to collect form data sent via the POST method.

4. To read an entire file into a string, use the file_get_contents() function.

5. In fopen("file.txt", "a"), the mode a means append — write data at the end without erasing existing content.

6. The $_FILES superglobal array contains information about uploaded files.

7. fclose() is used to close an open file handle.

8. The function move_uploaded_file() moves an uploaded file from temporary storage to a permanent location.

9. htmlspecialchars() converts special characters to HTML entities to prevent cross-site scripting (XSS).

10. In $_FILES['upload']['name'], the key name stores the original filename from the user's computer.


III. True or False

1. GET method sends form data in the URL query string. — True. Data is appended to the URL as key=value pairs separated by &.

2. POST method has a practical size limit of 2048 characters. — False. POST has no fixed size limit; the 2048-character limit applies to GET (URL length).

3. fopen() returns a file handle resource on success and FALSE on failure. — True.

4. The w mode in fopen() preserves existing file content. — False. The w mode truncates (erases) existing content. Use a mode to preserve content.

5. $_REQUEST contains data from GET, POST, and COOKIES. — True. It is a combined superglobal but is less secure and not recommended for production code.

6. A file upload form must use method="GET". — False. File uploads must use method="POST" along with enctype="multipart/form-data".

7. fgets() reads a single line from a file. — True. It reads until a newline or EOF.

8. fwrite() can only write to newly created files. — False. It can write to any file opened in a writable mode (w, w+, a, a+, r+).

9. It is good practice to always close a file with fclose() after operations. — True. Closing releases the file handle and ensures data is flushed to disk.

10. The a+ mode allows both reading and appending. — True. a+ opens for reading and writing, with the pointer at the end for writing.


IV. Match the Following

Set A

No.Column ANo.Column B
1$_GETdURL query string data
2$_POSTeHTTP body data
3$_FILESaUploaded file information
4fopen()cOpens a file handle
5fclose()bCloses a file handle

Set B

No.Column ANo.Column B
1mode "r"dRead only
2mode "w"eWrite only (truncate)
3mode "a"aAppend
4htmlspecialchars()cPrevent XSS
5move_uploaded_file()bMove uploaded file to destination

V. Short Answer Questions

1. Differentiate between GET and POST methods.
Answer
FeatureGETPOST
Data locationURL query stringHTTP request body
VisibilityVisible in address barNot visible
Size limit~2048 charactersNo practical limit
SecurityLess secure (data exposed)More secure (data hidden)
CachingCan be bookmarked/cachedNot cached
Use caseSearch queries, non-sensitive dataLogin forms, file uploads, sensitive data

2. Write an HTML form that collects a student's name and age, and sends it via POST to "process.php".
<form action="process.php" method="POST">
    <label>Name:</label>
    <input type="text" name="name" required><br>
    <label>Age:</label>
    <input type="number" name="age" required><br>
    <input type="submit" value="Submit">
</form>

3. Write a PHP snippet to read and display the contents of a file named "notes.txt".
<?php
$filename = "notes.txt";
if (file_exists($filename)) {
    $content = file_get_contents($filename);
    echo nl2br($content);
} else {
    echo "File not found.";
}
?>
Answer

nl2br() converts newlines to <br> tags for proper HTML display.


4. List the common file modes in fopen().
Answer
ModeDescription
rRead only; pointer at beginning
r+Read + Write; pointer at beginning
wWrite only; creates file if missing, truncates if exists
w+Read + Write; creates if missing, truncates if exists
aWrite only (append); pointer at end
a+Read + Write (append); pointer at end for writing

5. Explain the $_FILES superglobal with its keys.
Answer

When a file is uploaded, $_FILES['fieldname'] contains:

  • name — original filename on the client machine
  • type — MIME type (e.g., image/jpeg)
  • tmp_name — temporary filename on the server
  • size — file size in bytes
  • error — error code (0 means no error)

Example:

<?php
$name = $_FILES['upload']['name'];
$tmp  = $_FILES['upload']['tmp_name'];
move_uploaded_file($tmp, "uploads/" . $name);
echo "File uploaded successfully!";
?>

6. What is form validation? Why is it important?
Answer

Form validation is the process of checking user input to ensure it meets expected criteria before processing. It is important because:

  • Security — prevents SQL injection, XSS, and other attacks.
  • Data integrity — ensures correct data types, ranges, and formats.
  • User experience — provides feedback for incorrect input.

Types:

  • Client-side — JavaScript validation (fast, can be bypassed).
  • Server-side — PHP validation (secure, cannot be bypassed).

Example server-side validation:

<?php
$name = trim($_POST['name']);
if (empty($name)) {
    echo "Name is required!";
} elseif (!preg_match("/^[a-zA-Z ]+$/", $name)) {
    echo "Name must contain only letters and spaces.";
}
?>

VI. Detailed Answer Questions

1. Explain the complete process of handling a form using PHP with an example.
Answer

Form handling in PHP involves two pages: the HTML form and the PHP processing script.

Step 1 — HTML Form (form.html):

<!DOCTYPE html>
<html>
<body>
<form action="process.php" method="POST">
    <label>Name:</label>
    <input type="text" name="username" required><br>
    <label>Email:</label>
    <input type="email" name="email" required><br>
    <label>Gender:</label>
    <input type="radio" name="gender" value="Male"> Male
    <input type="radio" name="gender" value="Female"> Female<br>
    <input type="submit" value="Register">
</form>
</body>
</html>

Step 2 — PHP Processing (process.php):

<?php
// Sanitize and retrieve data
$name    = htmlspecialchars(trim($_POST['username']));
$email   = filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL);
$gender  = $_POST['gender'];

// Validate
if (empty($name)) {
    die("Name is required.");
}
if (!$email) {
    die("Invalid email address.");
}

// Process (display)
echo "<h2>Registration Successful</h2>";
echo "Name: $name<br>";
echo "Email: $email<br>";
echo "Gender: $gender<br>";
?>

Key points: always validate and sanitize input on the server side, use htmlspecialchars() to prevent XSS, and use filter_var() for email validation.


2. Explain file handling operations in PHP — create, write, read, append, and close — with examples.
Answer

Opening a file:

$handle = fopen("data.txt", "w") or die("Cannot open file!");

Writing to a file (mode w — overwrites):

fwrite($handle, "Hello, World!\n");
fwrite($handle, "PHP File Handling\n");

Closing a file:

fclose($handle);

Reading from a file (mode r):

$handle = fopen("data.txt", "r") or die("Cannot open file!");
while (!feof($handle)) {
    $line = fgets($handle);
    echo $line . "<br>";
}
fclose($handle);

Appending to a file (mode a — adds without erasing):

$handle = fopen("data.txt", "a") or die("Cannot open file!");
fwrite($handle, "New line appended\n");
fclose($handle);

Shortcut methods:

// Read entire file
$content = file_get_contents("data.txt");

// Write entire file
file_put_contents("data.txt", "Overwrites everything");

Important: Always close files with fclose() to free resources and ensure data is written to disk.


3. Write a complete PHP program for file upload with validation.
Answer

HTML Form (upload.html):

<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="POST" enctype="multipart/form-data">
    <label>Select file:</label>
    <input type="file" name="myfile" required><br>
    <input type="submit" value="Upload">
</form>
</body>
</html>

PHP Processing (upload.php):

<?php
$targetDir  = "uploads/";
$targetFile = $targetDir . basename($_FILES["myfile"]["name"]);
$fileType   = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

// Check if file already exists
if (file_exists($targetFile)) {
    die("Sorry, file already exists.");
}

// Limit file size (2MB max)
if ($_FILES["myfile"]["size"] > 2000000) {
    die("Sorry, file is too large (max 2MB).");
}

// Allow only certain formats
$allowed = array("jpg", "png", "gif", "pdf", "txt");
if (!in_array($fileType, $allowed)) {
    die("Sorry, only JPG, PNG, GIF, PDF, and TXT files are allowed.");
}

// Upload file
if (move_uploaded_file($_FILES["myfile"]["tmp_name"], $targetFile)) {
    echo "The file " . htmlspecialchars(basename($_FILES["myfile"]["name"])) 
         . " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}
?>

Validations performed: file existence check, size limit (2MB), file type restriction, and secure upload using move_uploaded_file().


4. Compare $_GET, $_POST, and $_REQUEST with examples.
Answer
Feature$_GET$_POST$_REQUEST
Data sourceURL query stringHTTP request bodyGET + POST + COOKIE
VisibilityVisible in URLHiddenCombined
SecurityLowMediumLow (priority order applies)
Size limit~2048 charsNo practical limitDepends on method
BookmarkingCan be bookmarkedCannotDepends on method
Use caseSearch, filtersForms, logins, uploadsQuick prototyping

Example — $_GET:

<!-- URL: process.php?city=Chennai&state=TN -->
<?php
$city  = $_GET['city'];    // Chennai
$state = $_GET['state'];   // TN
echo "City: $city, State: $state";
?>

Example — $_POST:

<form action="process.php" method="POST">
    <input type="password" name="pwd">
    <input type="submit">
</form>
<?php
$pwd = $_POST['pwd'];  // Data not visible in URL
?>

Example — $_REQUEST:

<?php
// Works for both GET and POST
$city = $_REQUEST['city'];
?>

Best practice: Use $_GET for non-sensitive data (searches, pagination), $_POST for sensitive data (passwords, file uploads). Avoid $_REQUEST in production due to security concerns.


Common Mistakes

1. Forgetting enctype="multipart/form-data" for file uploads — the file will not be sent; $_FILES will be empty.

2. Not validating/sanitizing form data — raw user input can contain XSS or SQL injection attacks. Always use htmlspecialchars() and filter_var().

3. Confusing fopen() modes w and a — w truncates the file (erases content); a appends without erasing.

4. Not closing files with fclose() — leaves file handles open, may cause data loss or lock issues.

5. Using $_GET for sensitive data — passwords and personal data should always use $_POST.

6. Not checking if a file exists before reading — always use file_exists() before fopen() to avoid errors.

7. Trusting the $_FILES['name'] for saving — always sanitize the filename; a malicious user can set a dangerous name. Use basename() to strip path components.


Exam Checklist

  • [ ] Can write a complete HTML form with action, method, and input elements
  • [ ] Can differentiate GET vs POST (visibility, security, size, use cases)
  • [ ] Know the $_GET, $_POST, $_REQUEST, and $_FILES superglobals
  • [ ] Can write PHP code to retrieve and display form data
  • [ ] Can perform server-side validation (empty check, regex, filter_var)
  • [ ] Can use htmlspecialchars() to prevent XSS
  • [ ] Know all fopen() modes (r, w, a, r+, w+, a+) and their behavior
  • [ ] Can write PHP programs for file create, read, write, append, and close
  • [ ] Can implement a file upload with validation (size, type, existence check)
  • [ ] Can explain the complete flow: HTML form → PHP processing → output/display

Frequently Asked Questions

$_GET appends data to the URL (visible, limited length, not secure); $_POST sends data in the HTTP body (invisible, no length limit, more secure).
← Browse all Class 12 Exercise Solutions

More exercise solutions