Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

3. Working with Forms

Lesson 17 of 36 in the free Web Based Programming notes on Siksha Sarovar, written by Rohit Jangra.

Handling HTML Forms in PHP: Methods, Controls & Validation

Study Deep: Form Security Best Practices

When handling forms in a University exam or professional project, security is as important as functionality.

  1. Cross-Site Scripting (XSS) Prevention: Always use htmlspecialchars() when displaying user-submitted data to prevent malicious scripts from executing in the browser.
  2. CSRF Protection: Use hidden tokens to ensure that form submissions originate from your own site.
  3. Empty Field Checks: Never assume a user will fill out all fields. Always use empty() or isset() before processing.
  4. Data Sanitization: Use trim() to remove accidental whitespace and stripslashes() to clean up data.

1. What is an HTML Form?

An HTML Form is a section of a web page that contains interactive controls (text boxes, checkboxes, buttons, etc.) allowing users to input data and submit it to a web server for processing.

Key Form Attributes:

AttributePurposeExample
actionSpecifies the URL of the PHP script that will process the form dataaction="process.php"
methodSpecifies how data is sent: GET or POSTmethod="post"
enctypeRequired for file uploads: multipart/form-dataenctype="multipart/form-data"

2. Form Handling Process (Step-by-Step)

  1. Design: HTML form is created with appropriate input controls.
  2. User Input: The user fills in the form fields in the browser.
  3. Submission: User clicks the Submit button.
  4. HTTP Request: The browser packages the form data and sends it to the server URL specified in action.
  5. PHP Processing: The PHP script reads values from $_GET or $_POST.
  6. Validation: PHP checks that the data is correct and complete.
  7. Response: After processing (saving, emailing, etc.), PHP sends back an HTML response page.

3. GET vs POST Methods — Detailed Comparison

FeatureGET MethodPOST Method
VisibilityData visible in URL (e.g., page.php?name=Rohit)Data hidden from URL bar
SecurityLow — NEVER use for passwords or sensitive dataHigher — data sent in HTTP request body
Data LimitLimited (~2000 characters)No practical limit — can send large files
CachingCan be cached and bookmarkedCannot be cached or bookmarked
Data TypeOnly ASCII charactersBinary data allowed (images, documents)
Browser HistoryURL (with data) is stored in historyData NOT stored in browser history
IdempotentYes (safe to repeat)No (repeated submission = repeated action)
Best Used ForFetching data (search forms, filters, pagination)Submitting data (login, registration, file upload)

4. A Complete Form Example

HTML File (form.html):

<form method="POST" action="process.php">
  <label>Name:</label>
  <input type="text" name="fname" placeholder="Enter your name"><br>

  <label>Email:</label>
  <input type="email" name="email" placeholder="Enter email"><br>

  <label>Gender:</label>
  <input type="radio" name="gender" value="Male"> Male
  <input type="radio" name="gender" value="Female"> Female<br>

  <label>Skills:</label>
  <input type="checkbox" name="skills[]" value="PHP"> PHP
  <input type="checkbox" name="skills[]" value="JavaScript"> JS<br>

  <label>City:</label>
  <select name="city">
    <option value="Delhi">Delhi</option>
    <option value="Mumbai">Mumbai</option>
  </select><br>

  <textarea name="message" placeholder="Your message..."></textarea><br>
  <input type="submit" value="Submit">
</form>

PHP File (process.php):

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name   = htmlspecialchars($_POST['fname']);
  $email  = htmlspecialchars($_POST['email']);
  $gender = $_POST['gender'] ?? 'Not specified';
  $skills = isset($_POST['skills']) ? implode(", ", $_POST['skills']) : "None";
  $city   = $_POST['city'];

  echo "Name: $name<br>";
  echo "Email: $email<br>";
  echo "Gender: $gender<br>";
  echo "Skills: $skills<br>";
  echo "City: $city<br>";
}
?>

5. PHP Form Validation

Definition: Form validation is the process of checking that submitted form data is correct, complete, and safe before using it.

Why Validate?

  • Prevent empty submissions.
  • Ensure correct data format (e.g., valid email).
  • Protect against malicious input (XSS attacks).

Common Validation Functions:

FunctionPurposeExample
empty($var)Check if variable is empty/nullempty($_POST['name'])
isset($var)Check if variable is set and not nullisset($_POST['email'])
filter_var($var, FILTER)Validate/sanitize using a filterfilter_var($email, FILTER_VALIDATE_EMAIL)
htmlspecialchars($str)Convert special chars to HTML entities (prevents XSS)htmlspecialchars($_POST['name'])
trim($str)Remove extra whitespacetrim($_POST['name'])
preg_match($pattern, $str)Match a regular expressionpreg_match("/^[A-Za-z]+$/", $name)

Complete Validation Example:

<?php
$nameErr = $emailErr = "";
$name = $email = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } else {
    $name = htmlspecialchars(trim($_POST["name"]));
  }

  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } elseif (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
    $emailErr = "Invalid email format";
  } else {
    $email = htmlspecialchars(trim($_POST["email"]));
  }
}
?>

6. The $_REQUEST Superglobal

$_REQUEST is a superglobal that contains the combined contents of $_GET, $_POST, and $_COOKIE. It is flexible but less secure than using specific method arrays.

// Works for BOTH GET and POST requests
$name = $_REQUEST['fname'];

When to use: Only when you genuinely need to handle both GET and POST. For most forms, use the specific $_POST or $_GET.