Mastering PHP: From Basics to Building Dynamic Web Applications

0 0 0 0 0

Chapter 5: Working with Forms and User Input

🔹 1. Introduction

Handling user input is one of the most critical tasks in any web application. From login forms to feedback submissions, PHP makes it easy to:

  • Capture user input through forms
  • Process and validate that data
  • Secure the app from common attacks like XSS and injection

In this chapter, you'll learn how to build interactive and secure forms in PHP, covering both GET and POST methods, as well as how to validate and sanitize inputs.


🔹 2. Creating a Simple HTML Form

Example:

<form method="post" action="welcome.php">

  Name: <input type="text" name="username">

  <input type="submit">

</form>

This form sends the data to welcome.php using the POST method.


🔹 3. Retrieving Form Data in PHP

PHP uses superglobal arrays to access form data:

Method

Variable

Description

POST

$_POST

Hidden from URL, preferred for sensitive info

GET

$_GET

Appends data to URL, visible and bookmarkable

Example:

$username = $_POST['username'];

echo "Welcome, $username!";


🔹 4. Using $_SERVER["REQUEST_METHOD"]

This helps determine if the form has been submitted:

if ($_SERVER["REQUEST_METHOD"] == "POST") {

  $username = $_POST['username'];

  echo "Hi, $username!";

}

This ensures the code runs only when the form is submitted.


🔹 5. Validating Form Input

Common Validation Checks:

  • Required fields
  • Valid email format
  • Password length
  • Matching confirm password

if (empty($_POST["email"])) {

  echo "Email is required.";

} elseif (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {

  echo "Invalid email format.";

}


🔹 6. Sanitizing User Input

Use these to clean data before processing or storing:

Function

Purpose

htmlspecialchars()

Prevent XSS by encoding HTML chars

trim()

Remove spaces from both ends

stripslashes()

Remove backslashes

Example:

$name = htmlspecialchars(trim($_POST["name"]));


🔹 7. Displaying Errors and User Feedback

if (empty($name)) {

  $error = "Name is required";

} else {

  $success = "Thank you, $name!";

}

php

CopyEdit

if (isset($error)) {

  echo "<p style='color:red;'>$error</p>";

}


🔹 8. Complete Example: Contact Form

HTML + PHP:

<form method="post" action="">

  Name: <input type="text" name="name">

  Email: <input type="text" name="email">

  <input type="submit">

</form>

 

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

  $name = htmlspecialchars(trim($_POST["name"]));

  $email = htmlspecialchars(trim($_POST["email"]));

 

  if (empty($name) || empty($email)) {

    echo "All fields are required.";

  } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

    echo "Invalid email.";

  } else {

    echo "Thanks $name! We’ll contact you at $email.";

  }

}

?>


🔹 9. Using GET Method for Search Forms

Example:

<form method="get">

  Search: <input type="text" name="q">

  <input type="submit">

</form>

 

<?php

if (isset($_GET["q"])) {

  echo "You searched for: " . htmlspecialchars($_GET["q"]);

}

?>

GET is ideal for search, filters, and navigation where you want URLs to be shareable.


🔹 10. Summary Table: Form Handling Essentials

Task

PHP Function or Method

Check method

$_SERVER["REQUEST_METHOD"]

Access POST data

$_POST['name']

Access GET data

$_GET['search']

Validate email

filter_var($email, FILTER_VALIDATE_EMAIL)

Sanitize text

htmlspecialchars(trim($input))

Error display

if(isset($error)) { echo $error; }



Back

FAQs


1. What is PHP used for?

PHP is primarily used for creating dynamic web pages and server-side applications such as login systems, e-commerce platforms, and CMSs.

2. Is PHP still relevant in 2025?

Absolutely. PHP continues to power most of the web and is essential in WordPress, Laravel, and web hosting environments.

3. Do I need to install anything to run PHP?

Yes — you can install XAMPP, MAMP, Laragon, or PHP CLI for local development.

4. What databases work with PHP?

MySQL is the most commonly used with PHP, but it also supports PostgreSQL, SQLite, and others.

5. What’s the difference between PHP and JavaScript?

PHP is a server-side scripting language, while JavaScript is primarily client-side, running in the browser.

6. Can I use PHP with HTML?

Yes PHP is often embedded inside HTML to create dynamic pages

7. What is a PHP file extension?

PHP files have the .php extension and are executed on the server.

8. How do I send data from a form to PHP?

Use method="POST" or method="GET" in your form and access data in PHP using $_POST or $_GET.

9. Is PHP good for building APIs?

Yes — PHP can be used to build RESTful APIs, especially with frameworks like Laravel or Slim.

10. What are some popular PHP frameworks?

Laravel, Symfony, CodeIgniter, Zend, and Slim are among the most used PHP frameworks.