Web Development /PHP Programming / Lesson
Web Development

GET and POST

Learn how PHP uses GET and POST to receive data from web forms and URLs, understand their differences, access submitted values safely, validate incoming requests, and choose the appropriate method for different web application tasks.

🎯

Learning Objectives

["Explain the purpose of the HTTP GET and POST methods.","Understand how GET data is transferred through the URL query string.","Understand how POST data is transferred through the HTTP request body.","Access GET values using the PHP $_GET superglobal.","Access POST values using the PHP $_POST superglobal.","Build simple HTML forms using GET and POST.","Understand the difference between GET and POST in practical applications.","Validate and normalize incoming GET and POST values.","Understand why POST should be used for state-changing operations.","Apply output escaping when displaying GET or POST values.","Understand that POST does not automatically make sensitive information secure.","Use appropriate security controls when processing user-submitted data."]

📖

Lesson Content

Introduction to GET and POST

When users interact with a web application, information often needs to
travel from the browser to the server. PHP provides special superglobal
arrays that make submitted request data available to server-side code.

Two of the most important HTTP methods used when working with PHP are
GET and POST.

These methods are commonly used with HTML forms, search interfaces,
filters, login systems, registration forms, application forms, and
many other web features.

1. What Is GET?

The HTTP GET method is commonly used to request information
from a server. When form data is submitted using GET, the submitted
values are normally included in the URL as a query string.

For example, a request might look like:

https://example.com/search.php?keyword=php

In this example, keyword=php is part of the query string.

2. The PHP $_GET Superglobal

PHP provides the $_GET superglobal array for accessing
values submitted through the GET method.

<?php

$keyword = $_GET['keyword'] ?? '';

echo htmlspecialchars(
    $keyword,
    ENT_QUOTES,
    'UTF-8'
);

?>

The null coalescing operator prevents an undefined-key warning when
the expected value has not been provided.

3. Creating a GET Form

An HTML form can use GET by setting the form’s method attribute to
get.

<form method="get" action="search.php">

    <label for="keyword">
        Search
    </label>

    <input
        type="search"
        id="keyword"
        name="keyword"
    >

    <button type="submit">
        Search
    </button>

</form>

If the user enters PHP, the browser may generate a URL
similar to:

search.php?keyword=PHP

4. GET Query Strings

A query string begins after the question mark in a URL.

products.php?category=books

Multiple values can be included using an ampersand.

products.php?category=books&page=2

PHP can access the values using their parameter names.

<?php

$category = $_GET['category'] ?? '';
$page = $_GET['page'] ?? '';

?>

5. GET Is Useful for Searches and Filters

GET is particularly useful when the submitted information describes
what information the user wants to retrieve.

Common examples include:

  • Search pages
  • Product filters
  • Category pages
  • Pagination
  • Sorting options
  • Public resource queries

Because the values are represented in the URL, a GET request can often
be bookmarked or shared.

6. What Is POST?

The HTTP POST method is commonly used when data is being
submitted to the server for processing or when an operation may change
server-side state.

Unlike GET, POST data is normally transmitted in the HTTP request body
rather than being appended to the URL.

Examples include:

  • Registration forms
  • Login forms
  • Contact forms
  • Creating records
  • Updating records
  • Submitting applications

7. The PHP $_POST Superglobal

PHP provides the $_POST superglobal array for accessing
values submitted through POST.

<?php

$name = $_POST['name'] ?? '';

echo htmlspecialchars(
    $name,
    ENT_QUOTES,
    'UTF-8'
);

?>

8. Creating a POST Form

A form can submit data using POST by setting the method attribute to
post.

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

    <label for="name">
        Full Name
    </label>

    <input
        type="text"
        id="name"
        name="name"
    >

    <button type="submit">
        Submit
    </button>

</form>

When the form is submitted, PHP can retrieve the value through
$_POST.

9. Checking the Request Method

Before processing submitted data, it is good practice to determine
which HTTP method was used.

<?php

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

    $name = trim($_POST['name'] ?? '');

    echo htmlspecialchars(
        $name,
        ENT_QUOTES,
        'UTF-8'
    );
}

?>

This allows the application to separate the initial page request from
the form-processing request.

10. GET Versus POST

GETPOST
Values are normally included in the URL.Values are normally included in the request body.
Useful for searches and filters.Useful for submitting or changing data.
URLs can be bookmarked and shared.Submitted values are not normally displayed in the URL.
Should not be used for sensitive information.Still requires HTTPS and proper security controls.
Often used for retrieving resources.Often used for operations that submit data.

11. GET Data Is Visible in the URL

Consider the following URL:

search.php?keyword=javascript

The keyword is visible in the browser’s address bar.

This makes GET convenient for search and filtering, but it also means
GET should not be used for passwords or other sensitive information.

12. POST Does Not Mean Encrypted

A common beginner mistake is believing that POST automatically makes
submitted information secure.

POST changes how data is transmitted in the HTTP request, but it does
not provide encryption by itself.

Applications handling sensitive information should use HTTPS and
appropriate authentication, authorization, validation, and security
controls.

13. Reading GET Values Safely

GET values originate outside the trusted server-side application and
should therefore be treated as untrusted input.

<?php

$search = trim($_GET['search'] ?? '');

echo htmlspecialchars(
    $search,
    ENT_QUOTES,
    'UTF-8'
);

?>

Trimming can normalize surrounding whitespace, while
htmlspecialchars() is appropriate when displaying the
value in an HTML context.

14. Reading POST Values Safely

<?php

$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');

if ($name === '') {
    echo 'Name is required.';
}

if (
    filter_var(
        $email,
        FILTER_VALIDATE_EMAIL
    ) === false
) {
    echo 'Enter a valid email address.';
}

?>

The application should validate POST data before using it for
important operations.

15. GET and Type Handling

Values received through HTTP requests should not automatically be
assumed to have the expected type or format.

For example, a page number can be validated as an integer.

<?php

$page = filter_input(
    INPUT_GET,
    'page',
    FILTER_VALIDATE_INT
);

if ($page === false || $page === null) {
    $page = 1;
}

echo $page;

?>

16. POST and Required Values

A POST request may contain missing or unexpected fields. PHP code
should therefore handle missing values safely.

<?php

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

    $name = trim($_POST['name'] ?? '');

    if ($name === '') {
        echo 'Name is required.';
    }
}

?>

17. GET With Multiple Parameters

A GET request can contain several query parameters.

students.php?course=web-development&page=2&sort=name

PHP can retrieve each parameter independently.

<?php

$course = $_GET['course'] ?? '';
$page = $_GET['page'] ?? '';
$sort = $_GET['sort'] ?? '';

?>

18. Validating Allowed Values

If an application accepts only a limited number of values, validate
the submitted value against an allow-list.

<?php

$allowedCourses = [
    'web-development',
    'data-analysis',
    'cyber-security'
];

$course = $_GET['course'] ?? '';

if (!in_array($course, $allowedCourses, true)) {
    echo 'Invalid course.';
}

?>

This is safer than assuming that the browser will only submit values
supplied by the application’s interface.

19. GET and Links

GET parameters can also be created through links.

<a href="courses.php?course=web-development">
    Web Development
</a>

PHP can then read the selected course.

<?php

$course = $_GET['course'] ?? '';

?>

This pattern is commonly used for category navigation, filtering, and
resource selection.

20. POST for Creating Data

Suppose a student submits a registration form.

<form method="post">

    <input
        type="text"
        name="student_name"
    >

    <input
        type="email"
        name="email"
    >

    <button type="submit">
        Register
    </button>

</form>

The server can process the submitted values using
$_POST.

21. Never Trust POST Just Because It Came From a Form

The browser interface is not the security boundary of an application.
A client can send requests directly without using the application’s
normal form.

Therefore, server-side code should always validate important POST
values.

<?php

$name = trim($_POST['name'] ?? '');

if ($name === '') {
    echo 'A name is required.';
    exit;
}

?>

22. GET and POST With HTML Escaping

If request data is displayed in HTML, it should be escaped according
to the output context.

<?php

$message = $_GET['message'] ?? '';

echo htmlspecialchars(
    $message,
    ENT_QUOTES,
    'UTF-8'
);

?>

This helps prevent submitted text from being interpreted as HTML.

23. GET and POST With Forms

A single application can use both methods for different tasks.

For example, a course website could use GET for searching courses:

<form method="get" action="courses.php">

    <input
        type="search"
        name="search"
    >

    <button type="submit">
        Search
    </button>

</form>

The same website could use POST when submitting an enrollment form:

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

    <input
        type="text"
        name="student_name"
    >

    <input
        type="email"
        name="email"
    >

    <button type="submit">
        Enroll
    </button>

</form>

24. GET for Filtering

GET works well for filtering because the filter state can be
represented in the URL.

students.php?course=web-development&status=active

A user can potentially copy this URL and share the same filter state
with another person.

25. POST for State-changing Operations

Operations that create, update, or delete server-side data should
generally use POST or another method designed for state-changing
operations rather than GET.

For example, deleting a student should not be implemented as a simple
GET link such as:

delete-student.php?id=25

State-changing actions require appropriate authentication,
authorization, request validation, and CSRF protection.

26. GET and Browser History

Because GET parameters appear in URLs, they may become part of browser
history and other systems that record URLs.

This is another reason sensitive information should not be placed in
GET query parameters.

27. GET and Bookmarking

One useful feature of GET is that a URL containing query parameters
can often be bookmarked.

For example:

courses.php?category=programming

A user can return to the URL and request the same category again.

28. POST and Refreshing a Page

After a POST request, applications often use the
Post/Redirect/Get pattern.

The basic idea is:

  1. User submits a POST request.
  2. Server validates and processes the data.
  3. Server redirects the browser to another URL.
  4. Browser makes a new GET request.

This can help prevent accidental duplicate submissions when users
refresh the resulting page.

29. Post/Redirect/Get Example

<?php

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

    $name = trim($_POST['name'] ?? '');

    if ($name !== '') {

        // Process the data here.

        header('Location: success.php');
        exit;
    }
}

?>

In WordPress applications, redirects should normally use WordPress
functions such as wp_safe_redirect() where appropriate.

30. GET and POST Security Checklist

  • Treat all request data as untrusted.
  • Validate important input on the server.
  • Normalize input where appropriate.
  • Escape output according to its context.
  • Use HTTPS for sensitive applications.
  • Do not place passwords in GET parameters.
  • Do not use GET for destructive state-changing actions.
  • Use CSRF protection for protected state-changing forms.
  • Check authentication and authorization where required.
  • Use prepared database queries.

31. Practical Search Example Using GET

<?php

$search = trim($_GET['search'] ?? '');

?>

<form method="get">

    <label for="search">
        Search Courses
    </label>

    <input
        type="search"
        id="search"
        name="search"
        value="<?php echo htmlspecialchars(
            $search,
            ENT_QUOTES,
            'UTF-8'
        ); ?>"
    >

    <button type="submit">
        Search
    </button>

</form>

<?php

if ($search !== '') {

    echo '<p>Searching for: ';

    echo htmlspecialchars(
        $search,
        ENT_QUOTES,
        'UTF-8'
    );

    echo '</p>';
}

?>

32. Practical Registration Example Using POST

<?php

$errors = [];

$name = '';
$email = '';

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

    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');

    if ($name === '') {
        $errors[] = 'Name is required.';
    }

    if (
        filter_var(
            $email,
            FILTER_VALIDATE_EMAIL
        ) === false
    ) {
        $errors[] = 'A valid email address is required.';
    }

    if (empty($errors)) {
        echo 'Registration submitted successfully.';
    }
}

?>

<form method="post">

    <label for="name">
        Full Name
    </label>

    <input
        type="text"
        id="name"
        name="name"
        value="<?php echo htmlspecialchars(
            $name,
            ENT_QUOTES,
            'UTF-8'
        ); ?>"
    >

    <label for="email">
        Email
    </label>

    <input
        type="email"
        id="email"
        name="email"
        value="<?php echo htmlspecialchars(
            $email,
            ENT_QUOTES,
            'UTF-8'
        ); ?>"
    >

    <button type="submit">
        Register
    </button>

</form>

33. Common GET and POST Mistakes

  • Assuming GET and POST values always exist.
  • Displaying request data without output escaping.
  • Using GET for passwords or other sensitive information.
  • Using GET for destructive operations.
  • Trusting HTML validation without server-side validation.
  • Assuming POST automatically encrypts information.
  • Failing to validate allowed values.
  • Ignoring authorization checks.
  • Failing to protect state-changing forms against CSRF.
  • Building SQL queries by concatenating request data.

34. Best Practices

  • Use GET when retrieving or filtering information.
  • Use POST when submitting data that may change server-side state.
  • Validate all important request values on the server.
  • Use $_GET and $_POST carefully.
  • Use null coalescing when handling optional fields.
  • Escape values before displaying them in HTML.
  • Use HTTPS for sensitive information.
  • Use CSRF protection for protected state-changing operations.
  • Use authorization checks before privileged actions.
  • Use prepared database queries.
  • Consider Post/Redirect/Get after successful POST processing.

Lesson Summary

GET and POST are two fundamental HTTP methods used when building PHP
web applications.

GET data is normally included in the URL and is useful for searches,
filters, pagination, and other retrieval-oriented operations. PHP
provides the $_GET superglobal for accessing this data.

POST data is normally transmitted in the request body and is commonly
used when submitting information or performing operations that change
server-side state. PHP provides the $_POST superglobal
for accessing this data.

Neither method should be treated as automatically trustworthy or
secure. Professional PHP applications validate request data, escape
output appropriately, use HTTPS where necessary, protect state-changing
operations against CSRF, verify authorization, and use safe database
practices.

💻

Code Example

<?php

$errors = [];

$name = '';
$email = '';
$course = '';

$allowedCourses = [
    'web-development',
    'data-analysis',
    'cyber-security',
];

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

    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $course = $_POST['course'] ?? '';

    if ($name === '') {
        $errors['name'] = 'Name is required.';
    }

    if (
        filter_var(
            $email,
            FILTER_VALIDATE_EMAIL
        ) === false
    ) {
        $errors['email'] = 'A valid email address is required.';
    }

    if (!in_array($course, $allowedCourses, true)) {
        $errors['course'] = 'Please select a valid course.';
    }

    if (empty($errors)) {

        // Process the valid POST data here.

        header('Location: success.php');
        exit;
    }
}

?>

<form method="post">

    <label for="name">
        Full Name
    </label>

    <input
        type="text"
        id="name"
        name="name"
        value="<?php echo htmlspecialchars(
            $name,
            ENT_QUOTES,
            'UTF-8'
        ); ?>"
    >

    <?php if (isset($errors['name'])) : ?>

        <p>
            <?php
            echo htmlspecialchars(
                $errors['name'],
                ENT_QUOTES,
                'UTF-8'
            );
            ?>
        </p>

    <?php endif; ?>

    <label for="email">
        Email
    </label>

    <input
        type="email"
        id="email"
        name="email"
        value="<?php echo htmlspecialchars(
            $email,
            ENT_QUOTES,
            'UTF-8'
        ); ?>"
    >

    <?php if (isset($errors['email'])) : ?>

        <p>
            <?php
            echo htmlspecialchars(
                $errors['email'],
                ENT_QUOTES,
                'UTF-8'
            );
            ?>
        </p>

    <?php endif; ?>

    <label for="course">
        Course
    </label>

    <select id="course" name="course">

        <option value="">
            Select a course
        </option>

        <option
            value="web-development"
            <?php selected($course, 'web-development'); ?>
        >
            Web Development
        </option>

        <option
            value="data-analysis"
            <?php selected($course, 'data-analysis'); ?>
        >
            Data Analysis
        </option>

        <option
            value="cyber-security"
            <?php selected($course, 'cyber-security'); ?>
        >
            Cyber Security
        </option>

    </select>

    <?php if (isset($errors['course'])) : ?>

        <p>
            <?php
            echo htmlspecialchars(
                $errors['course'],
                ENT_QUOTES,
                'UTF-8'
            );
            ?>
        </p>

    <?php endif; ?>

    <button type="submit">
        Register
    </button>

</form>
⭐

Key Takeaways

["GET and POST are HTTP methods used to send or process information between a browser and a server.","GET values are normally included in the URL query string.","POST values are normally included in the HTTP request body.","PHP provides $_GET for GET request data and $_POST for POST request data.","GET is commonly useful for searches, filters, pagination, and retrieval-oriented requests.","POST is commonly used for submitting information and state-changing operations.","GET parameters should never be used for passwords or other sensitive information.","POST does not automatically encrypt data; HTTPS is still required for secure transmission.","All request data should be treated as untrusted and validated on the server.","Output escaping is required when displaying user-controlled request data in HTML.","State-changing operations should use CSRF protection and appropriate authorization checks.","The Post\/Redirect\/Get pattern can help reduce accidental duplicate form submissions."]

Enjoying this lesson?

Sign in to your Dwallnet Academy student account to track your learning progress and mark lessons as complete.

Sign In to Track Progress