Web Development courseLesson 5 of 20 · tap to see all lessons
Web Development · Beginner
PHP Forms and Git/GitHub: GET and POST, Validating Input, and Version Control Basics
Process HTML forms with PHP using GET and POST, validate and safely display input, then track your code with Git and publish it to GitHub with a README.
- Qyubie Learn Editorial Team
- Published
- 13 min read
Includes 2 quick checks you can do right here.
In lesson 2 you built forms, but nothing happened when you pressed Submit. In this lesson the server finally answers: PHP receives the data, checks it, and responds. In the second half you'll start using Git, the tool every developer uses to save versions of their code, and GitHub, where you'll submit your work for the rest of the course.
By the end of this lesson you will be able to:
- read form data sent with GET and POST,
- validate input and show helpful error messages,
- display user input safely,
- explain what Git is and set it up, and
- use
init,status,add,commit,push, andpull, and publish a repository with a README on GitHub.
GET and POST
A form's method decides how the browser sends the data (lesson 1):
GET | POST | |
|---|---|---|
| Where the data goes | in the URL: search.php?q=php&page=2 | in the request body, not visible in the URL |
| Can be bookmarked or shared | yes | no |
| Size | limited (URLs should stay short) | large; files can be uploaded |
| Use for | reading: searches, filters, page numbers | changing something: sign-ups, logins, saving, deleting |
| In PHP | $_GET | $_POST |
$_GET and $_POST are superglobals: associative arrays PHP fills in for you, available everywhere. The keys are the name attributes of the form fields.
Reading GET data
A search form and the PHP that handles it:
<form action="search.php" method="get">
<input type="search" name="q" placeholder="Search subjects">
<button>Search</button>
</form>When the user searches for "web", the browser requests search.php?q=web, and search.php reads it:
<?php
$subjects = ["Web Development", "Data Structures", "Web Design", "Networking"];
$q = trim($_GET["q"] ?? "");
$results = array_filter($subjects, fn($s) => $q !== "" && stripos($s, $q) !== false);
echo "Results for \"" . htmlspecialchars($q) . "\":\n";
foreach ($results as $r) {
echo "- $r\n";
}
if (!$results) {
echo "No subjects found.\n";
}Output:
Results for "web":
- Web Development
- Web Design$_GET["q"] ?? ""gives an empty string when the page is opened without aq. Reading a missing key directly produces a warning.trim()removes spaces the user typed at the start or end.stripossearches without caring about upper- or lowercase.
Reading POST data
A form usually posts to itself: the same file shows the form and, when it's submitted, processes it. $_SERVER["REQUEST_METHOD"] tells you which case you're in.
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST["full_name"] ?? "");
$course = $_POST["course"] ?? "";
echo "<p>Thank you, " . htmlspecialchars($name) . ". You chose " . htmlspecialchars($course) . ".</p>\n";
} else {
echo "<p>Please fill in the form.</p>\n";
}
?>
<form method="post">
<input name="full_name">
<select name="course"><option>BSCS</option><option>BSIT</option></select>
<button>Send</button>
</form>Output after submitting "Ana Reyes" and "BSCS":
<p>Thank you, Ana Reyes. You chose BSCS.</p>
<form method="post">
<input name="full_name">
<select name="course"><option>BSCS</option><option>BSIT</option></select>
<button>Send</button>
</form>A form with no action submits to the current URL, which is how a page posts to itself.
Never trust input: validation
Anything in $_GET and $_POST comes from the user's browser, and the user controls it. They can skip your required attributes, edit the HTML in DevTools, or send a request with no form at all. So the server must check every value, even if the browser already did.
Validation answers: is it there, is it the right type, and is it in the allowed range or list? A common pattern collects all the errors, then shows them next to the form:
<?php
$errors = [];
$old = ["name" => "", "email" => "", "age" => "", "course" => ""];
$courses = ["BSCS", "BSIT"];
if ($_SERVER["REQUEST_METHOD"] === "POST") {
foreach ($old as $field => $_) {
$old[$field] = trim($_POST[$field] ?? "");
}
if ($old["name"] === "") {
$errors["name"] = "Please enter your name.";
} elseif (mb_strlen($old["name"]) < 2) {
$errors["name"] = "Your name looks too short.";
}
if (!filter_var($old["email"], FILTER_VALIDATE_EMAIL)) {
$errors["email"] = "Enter an email like juan@example.com.";
}
$age = filter_var($old["age"], FILTER_VALIDATE_INT, ["options" => ["min_range" => 18, "max_range" => 99]]);
if ($age === false) {
$errors["age"] = "Age must be a whole number from 18 to 99.";
}
if (!in_array($old["course"], $courses, true)) {
$errors["course"] = "Choose BSCS or BSIT.";
}
if (!$errors) {
echo "Registered!\n"; // later: save to the database (lesson 8)
}
}
foreach ($errors as $field => $message) {
echo "$field: $message\n";
}Output for a form posted with name "A", email "ana-at-mail", age 17, and course "BSN":
name: Your name looks too short.
email: Enter an email like juan@example.com.
age: Age must be a whole number from 18 to 99.
course: Choose BSCS or BSIT.The tools used:
filter_var($value, FILTER_VALIDATE_EMAIL)returns the email if it's valid, orfalse. Other filters check integers (with a range), floats, URLs, and booleans.in_array(..., true)checks a value against an allow-list. For selects and radio buttons, always check that the value is one you offered.- Keeping the typed values in
$oldlets you fill the form back in, so the user only fixes the wrong fields:
<input name="email" value="<?= htmlspecialchars($old["email"]) ?>">
<?php if (isset($errors["email"])): ?>
<p class="error"><?= $errors["email"] ?></p>
<?php endif; ?>Displaying input safely
Suppose a user types this as their name:
<script>alert('hacked')</script>If your page prints it with a plain echo $name, the browser runs the script for everyone who views the page. This attack is called cross-site scripting (XSS), and it can steal logins. The fix is to escape output:
<?php
$name = "<script>alert('hacked')</script>";
echo htmlspecialchars($name), "\n";Output:
<script>alert('hacked')</script>The browser now shows the text instead of running it. The rule is simple: validate input when it arrives, and escape it with htmlspecialchars() whenever you print it into HTML. (For databases, the matching rule is prepared statements, in lesson 8.)
Quick check
Redirect after POST
After a successful POST, don't print a page directly. If the user presses Refresh, the browser asks "Resubmit the form?" and might register them twice. Instead, redirect to a normal GET page:
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST" && !$errors) {
// ... save the data ...
header("Location: thank-you.php"); // a 302 redirect (lesson 1)
exit;
}header() must run before any output, even a blank line or a space before <?php, or PHP reports headers already sent. This pattern is called Post/Redirect/Get.
Version control with Git
Have you ever had files like project-final.zip, project-final2.zip, and project-FINAL-talaga.zip? Version control solves that. Git records snapshots of your project, called commits, so you can:
- see what changed, when, and why,
- go back to any earlier version when something breaks,
- work on new features in branches without breaking working code (lesson 10), and
- collaborate: several people change the same project and Git combines their work.
Git is the program on your computer. GitHub is a website that hosts Git repositories online, so your code is backed up, shareable, and ready for teamwork and deployment.
Install and configure Git
Download Git from git-scm.com and install it with the default options. Then, in a terminal (Git Bash, PowerShell, or VS Code's terminal), tell Git who you are. This name and email go into every commit you make:
git --version
git config --global user.name "Juan Dela Cruz"
git config --global user.email "juan@example.com"
git config --global init.defaultBranch mainUse the same email as your GitHub account, so GitHub links your commits to you.
The three areas
Git moves changes through three places:
working folder ──git add──▶ staging area ──git commit──▶ repository (history)
(files you edit) (what goes in the next commit) (saved snapshots)You choose exactly what goes into each commit by staging it first.
Your first repository
cd C:/xampp/htdocs/cs324
git init # start tracking this folder (creates a hidden .git folder)
git status # what's changed? (use it constantly)
git add index.php style.css # stage specific files...
git add . # ...or everything in the folder
git commit -m "Add registration form with validation"
git log --oneline # list the commitsA good commit message says what the change does, in the present tense: "Add login form", "Fix email validation". Avoid "update" or "asdf". Commit small, working steps, several times a day.
Ignoring files
Some files should never be committed: passwords, uploaded files, and installed packages. List them in a file named .gitignore in the project folder:
# .gitignore
.env
config.local.php
uploads/
node_modules/Never commit passwords or API keys. Once they're pushed, assume they're public.
Quick check
Publishing to GitHub
- Create an account at github.com.
- Click New repository. Name it (for example
cs324-labs), choose Public or Private, and leave "Add a README" unchecked if your folder already has commits. - GitHub shows the commands to connect your local repository. They look like this:
git remote add origin https://github.com/your-username/cs324-labs.git
git branch -M main
git push -u origin main- A remote is a copy of the repository somewhere else;
originis the usual name for the GitHub one. git pushuploads your new commits to GitHub. The-uremembers the connection, so next time a plaingit pushis enough.git pulldownloads commits from GitHub that you don't have yet, for example ones you pushed from the lab computer. Pull before you start working.- To get a repository onto a new computer,
git cloneit:git clone https://github.com/your-username/cs324-labs.git.
The first push asks you to sign in to GitHub in the browser. GitHub doesn't accept your account password on the command line.
The daily routine
git pull # get the latest
# ... edit, test in the browser ...
git status
git add .
git commit -m "Validate age and course on the registration form"
git pushREADME files
A README.md in the top folder is the first thing people see on your repository page. It's written in Markdown, a simple text format:
# CS 324 Lab: Student Registration
A PHP form that registers students and validates their input.
## Features
- Server-side validation of name, email, age, and course
- Safe output with htmlspecialchars
## How to run
1. Copy the folder to `C:\xampp\htdocs\`.
2. Start Apache in XAMPP.
3. Open http://localhost/cs324-labs/register.php
## Author
Juan Dela Cruz, BSCS 3A# makes headings, - makes bullet points, 1. numbered steps, and backticks mark code. A good README says what the project is, how to run it, and who made it. Your final project's README (lesson 19) will grow into full technical documentation.
Common mistakes
- Reading
$_POST["x"]without?? "", which warns when the field is missing. - Trusting browser validation and skipping server checks.
- Printing input without
htmlspecialchars(). - Output before
header(), causing headers already sent. - Committing passwords or
node_modules. Use.gitignore. - Forgetting to push, so the commits exist only on your laptop.
- Editing on two computers without
git pullfirst, which leads to conflicts (lesson 10).
Summary
GETsends data in the URL (for reading);POSTsends it in the body (for changing things). PHP reads them from$_GETand$_POST, keyed by each field'sname.- Validate every value on the server: present, right type, in range or in an allow-list.
filter_varandin_arrayhelp. - Escape output with
htmlspecialchars()to prevent XSS, and redirect after a successful POST. - Git saves snapshots:
git addstages,git commit -mrecords,git statusandgit loginspect. - GitHub hosts the repository:
git pushuploads,git pulldownloads,git clonecopies, andREADME.mdexplains the project.
That completes the preliminary topics. Next comes JavaScript, to make pages interactive in the browser.