Functions and form handling: user-defined functions; parameters and return values; variable scope (global vs. local); handling forms with $_GET and $_POST; basic input validation and sanitization

Functions package logic, scope keeps their variables private, and $_POST/$_GET carry a form's data into PHP: with validation and sanitization as the non-negotiable guard on every input.

12 min read · 10 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

The portal finally listens

Everything so far has been PHP talking to itself. Now the event portal must LISTEN: a student types their name and password into a form and submits. How does that typed data reach your PHP?

The answer is the superglobals $_POST and $_GET. And the moment real users can send you data, a hard rule kicks in: never trust user input. A login form is exactly where careless PHP becomes insecure PHP. This lesson connects forms to code, packages logic into FUNCTIONS, and guards every input with validation and sanitization.

Theory

Functions and scope

A function packages reusable logic:

function lineTotal($price, $qty) { return $price * $qty; }

Parameters carry data IN; return sends a value back; parameters can have defaults ($qty = 1).

Scope is the exam-worthy subtlety: variables inside a function are LOCAL by default and CANNOT see variables declared outside. A function does not automatically know about an outer $seats. To reach an outer (global) variable you must use the global keyword or the $GLOBALS array, but the CLEANER way is to pass data in as a PARAMETER. Local scope is a feature: it keeps functions self-contained and predictable.

Theory

$_GET and $_POST: the form's two doors

An HTML form's method decides how its data travels:

  • GET: data goes in the URL query string (portal.php?event=garba), visible and bookmarkable: for non-sensitive READS, arrives in $_GET
  • POST: data goes in the request BODY, not the URL: for submissions and sensitive data like passwords, arrives in $_POST

You read a field by its name: $_POST['username']. This is the same GET-vs-POST choice you met in BCA405-01's AJAX: reads and bookmarkable data use GET; anything private or state-changing (a login, a registration) uses POST, because you never want a password sitting in a URL.

Practical

login.php: form, POST, validate, sanitize

<!-- The form: method POST sends data in the body -->
<form method="POST" action="login.php">
  <input type="text" name="username">
  <input type="password" name="password">
  <button type="submit">Log in</button>
</form>

<?php
  if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // SANITIZE: clean the input
    $user = trim($_POST["username"] ?? "");
    $user = htmlspecialchars($user);   // neutralise HTML/scripts

    // VALIDATE: check it is acceptable
    if ($user === "") {
      echo "Username is required";
    } else {
      echo "Welcome, " . $user;
    }
  }
?>

Theory

Validation and sanitization: never trust input

Every value from $_GET/$_POST is a stranger's data, and could be blank, malformed, or malicious. Two guards, always:

  • Validation: is it ACCEPTABLE? Required field present? Is it a valid email (filter_var($e, FILTER_VALIDATE_EMAIL))? A number in range?
  • Sanitization: CLEAN it. trim() removes stray spaces; htmlspecialchars() neutralises HTML so someone cannot inject a <script> (an XSS attack); filter_var with a sanitize filter strips unwanted characters.

The rule is absolute: treat all user input as hostile until validated and sanitized. Skipping this is how real sites get hacked, and it is the security point examiners want to see.

Quiz

Why must the portal's login use POST rather than GET for the password?

  1. GET is faster, so POST is only for slow forms
  2. GET puts data in the visible URL; a password must travel in the request body (POST), not sit in the URL, history or logs
  3. POST can send more fields than GET
  4. There is no real difference; either is fine for passwords
Show the answer

GET puts data in the visible URL; a password must travel in the request body (POST), not sit in the URL, history or logs

GET encodes form data into the URL's query string, where it is visible on screen, saved in browser history, and often written into server logs: catastrophic for a password. POST puts the data in the request BODY, out of the URL, which is why sensitive and state-changing submissions use POST. This mirrors the GET-vs-POST rule from BCA405-01. Option A invents a speed difference. Option C states a real but secondary point (GET has length limits) that is not the security reason. Option D is dangerously false: never send credentials over GET. Reads and bookmarks use GET; submissions and secrets use POST.

Think first

The function that could not see the seats

A student writes function showSeats() { echo $seats; } with $seats = 350 declared OUTSIDE the function, and it prints nothing (with a warning). Why, and what is the clean fix? Then tap.

Show the answer

PHP variable SCOPE: variables inside a function are LOCAL, and a function cannot automatically see variables declared outside it, so $seats is undefined inside showSeats(), giving null and a warning. Two fixes: the quick-but-discouraged one is global $seats; inside the function (or $GLOBALS['seats']); the CLEAN one is to PASS it in: function showSeats($seats) { echo $seats; } and call showSeats(350). Passing parameters is preferred because it keeps the function self-contained and predictable, whereas relying on globals creates hidden dependencies. Local scope is protecting you: it forces you to be explicit about what data a function uses.

Watch out

Function and form traps

Assuming globals are visible: function variables are local; pass data as parameters.

Trusting raw input: always validate AND sanitize $_GET/$_POST before use.

Password over GET: never; use POST for credentials and any state change.

Missing key: $_POST['x'] on an unsubmitted field warns; use $_POST['x'] ?? '' (null coalescing) to default safely.

Echoing user input raw: htmlspecialchars() it first, or you open an XSS hole.

Theory

Unit 1 complete: the portal lives

You now have working Core PHP: setup, syntax, types, control flow, arrays, functions, and a real form processed safely. The event portal can greet a validated user. Unit 2 goes ADVANCED: handling files and uploads, JSON, cookies and sessions (so a login can be REMEMBERED across pages), sending email, and PHP's own object-oriented features with exceptions. The portal is about to gain memory and structure.

Summary

Key takeaways

  • Functions package logic: function name($params){ return $x; }; parameters carry data in, return sends a value back.
  • Scope: variables inside a function are LOCAL; pass data as parameters (preferred) rather than using global.
  • Form data arrives in $_GET (URL query string, visible reads) or $_POST (request body, submissions/secrets).
  • Read a field by its name: $_POST['username']; use POST for passwords and state changes, never GET.
  • Validation checks input is acceptable (required, valid email); sanitization cleans it (trim, htmlspecialchars, filter_var).
  • Never trust user input: validate and sanitize every value to prevent injection/XSS.
  • Memory hook: local scope by default, POST for secrets, and never trust a stranger's input.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Core PHP Programming

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Functions and form handling: user-defined functions; parameters and return values; variable scope (global vs. local); handling forms with $_GET and $_POST; basic input validation and sanitization · Web Framework and Services (Major-12) · Gri-Learn