Lesson 33 of 50 – PHP POST Method
66%

PHP POST Method

The HTTP POST method is commonly used to submit data to a server. In PHP, form fields submitted using the POST method can be accessed through the $_POST superglobal. It is often used for registration forms, contact forms, and other data-submission tasks.

1. What Is the POST Method?

The POST method sends submitted form data in the HTTP request body instead of placing it in the URL query string by default.

Example HTML form:

<form method="post" action="">
    <label for="studentName">Student Name:</label>
    <input type="text" id="studentName" name="student_name" required>

    <br><br>

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

The form uses method="post". Its student_name field can be accessed in PHP using:

$_POST['student_name']

POST does not automatically encrypt or secure data. Use HTTPS to protect information during transmission.

2. Reading POST Data in PHP

The $_POST array contains form fields submitted using POST with a supported form encoding.

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['student_name'] ?? '';

    echo "Student Name: " .
        htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
}
?>

<form method="post" action="">
    <label for="student_name">Enter Name:</label>
    <input type="text" id="student_name" name="student_name" required>

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

If the user enters Rahul, the output is:

Student Name: Rahul

The null coalescing operator (??) provides a fallback if the field is missing. The htmlspecialchars() function escapes special HTML characters before displaying user input.

3. Creating a POST Form with Multiple Fields

A form can submit several values together. Each input needs a name attribute so PHP can identify its value.

<form method="post" action="">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>

    <br><br>

    <label for="city">City:</label>
    <input type="text" id="city" name="city" required>

    <br><br>

    <label for="course">Course:</label>
    <input type="text" id="course" name="course" required>

    <br><br>

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

PHP can read the submitted values like this:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'] ?? '';
    $city = $_POST['city'] ?? '';
    $course = $_POST['course'] ?? '';

    echo "Name: " .
        htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . "<br>";

    echo "City: " .
        htmlspecialchars($city, ENT_QUOTES, 'UTF-8') . "<br>";

    echo "Course: " .
        htmlspecialchars($course, ENT_QUOTES, 'UTF-8');
}
?>

The PHP code reads each field separately and displays the submitted details safely.

4. Complete Student Registration Form

Save this complete example as student_registration.php. It displays a form and processes the submitted student details on the same page.

<?php
$name = '';
$email = '';
$course = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $course = trim($_POST['course'] ?? '');

    if ($name === '' || $email === '' || $course === '') {
        echo "<p>Please fill in all fields.</p>";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "<p>Please enter a valid email address.</p>";
    } else {
        echo "<h3>Registration Details</h3>";

        echo "Name: " .
            htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . "<br>";

        echo "Email: " .
            htmlspecialchars($email, ENT_QUOTES, 'UTF-8') . "<br>";

        echo "Course: " .
            htmlspecialchars($course, ENT_QUOTES, 'UTF-8');
    }
}
?>

<form method="post" action="">
    <label for="name">Student Name:</label>
    <input type="text" id="name" name="name" required>

    <br><br>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>

    <br><br>

    <label for="course">Course:</label>
    <select id="course" name="course" required>
        <option value="">Select Course</option>
        <option value="PHP">PHP</option>
        <option value="JavaScript">JavaScript</option>
        <option value="Python">Python</option>
    </select>

    <br><br>

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

This example validates required fields and checks the email format. A real registration system should also validate the course against an allowed list and save records using a database and prepared statements.

5. POST Method with a Calculator

A POST form can submit two numbers to a PHP program for calculation.

<?php
$result = null;
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $a = $_POST['a'] ?? '';
    $b = $_POST['b'] ?? '';

    if (
        $a === '' ||
        $b === '' ||
        !is_numeric($a) ||
        !is_numeric($b)
    ) {
        $error = 'Please enter two valid numbers.';
    } else {
        $result = (float)$a + (float)$b;
    }
}
?>

<form method="post" action="">
    <label for="a">First Number:</label>
    <input type="number" step="any" id="a" name="a" required>

    <br><br>

    <label for="b">Second Number:</label>
    <input type="number" step="any" id="b" name="b" required>

    <br><br>

    <button type="submit">Add Numbers</button>
</form>

<?php
if ($error !== '') {
    echo htmlspecialchars($error, ENT_QUOTES, 'UTF-8');
}

if ($result !== null) {
    echo "Sum: " . $result;
}
?>

If the user enters 10 and 20, the page displays:

Sum: 30

Always validate input on the server, even if the HTML form uses required and type="number".

6. POST Method with Radio Buttons

Radio buttons allow a user to select one option from a group. PHP receives the selected value through $_POST.

<?php
$gender = $_POST['gender'] ?? '';

$allowedGenders = ['Male', 'Female', 'Other'];

if (!in_array($gender, $allowedGenders, true)) {
    $gender = '';
}
?>

<form method="post" action="">
    <p>Select Gender:</p>

    <label>
        <input type="radio" name="gender" value="Male" required>
        Male
    </label>

    <br>

    <label>
        <input type="radio" name="gender" value="Female">
        Female
    </label>

    <br>

    <label>
        <input type="radio" name="gender" value="Other">
        Other
    </label>

    <br><br>

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

<?php
if ($gender !== '') {
    echo "Selected Option: " .
        htmlspecialchars($gender, ENT_QUOTES, 'UTF-8');
}
?>

If the user selects Male, the output is:

Selected Option: Male

The server validates the submitted value against the allowed options rather than trusting the browser.

7. POST Method with Checkboxes

Checkboxes can allow a user to select multiple options. Use an array name such as courses[] to receive multiple values.

<?php
$courses = $_POST['courses'] ?? [];

if (!is_array($courses)) {
    $courses = [];
}

$allowedCourses = [
    'PHP',
    'JavaScript',
    'Python'
];

$selectedCourses = [];

foreach ($courses as $course) {
    if (
        is_string($course) &&
        in_array($course, $allowedCourses, true)
    ) {
        $selectedCourses[] = $course;
    }
}
?>

<form method="post" action="">
    <p>Select Courses:</p>

    <label>
        <input type="checkbox" name="courses[]" value="PHP">
        PHP
    </label>

    <br>

    <label>
        <input type="checkbox" name="courses[]" value="JavaScript">
        JavaScript
    </label>

    <br>

    <label>
        <input type="checkbox" name="courses[]" value="Python">
        Python
    </label>

    <br><br>

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

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (count($selectedCourses) > 0) {
        echo "<h4>Selected Courses</h4><ul>";

        foreach ($selectedCourses as $course) {
            echo "<li>" .
                htmlspecialchars($course, ENT_QUOTES, 'UTF-8') .
                "</li>";
        }

        echo "</ul>";
    } else {
        echo "No valid course selected.";
    }
}
?>

The code checks that the submitted value is an array and filters the choices against the allowed course list before displaying them.

8. Difference Between GET and POST
GET Method POST Method
Parameters commonly appear in the URL. Form data is commonly sent in the request body.
Useful for searches and retrieving information. Commonly used for submitting or changing data.
URLs can be bookmarked with their query parameters. Submitted form body data is not normally part of the URL.
Use $_GET in PHP. Use $_POST for ordinary supported form encodings.

POST is not automatically secure. Use HTTPS, validate input on the server, and implement authentication and CSRF protection where appropriate.

For database updates, use prepared statements. For passwords, use PHP password-hashing functions rather than storing plain text.

9. Practical Example: Student Admission Form

This example combines a POST form, basic validation, and safe output. It does not save the student to a database.

<?php
$name = '';
$fatherName = '';
$mobile = '';
$course = '';
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $fatherName = trim($_POST['father_name'] ?? '');
    $mobile = trim($_POST['mobile'] ?? '');
    $course = $_POST['course'] ?? '';

    $allowedCourses = [
        'ADCA',
        'Web Development',
        'Tally Prime'
    ];

    if (
        $name === '' ||
        $fatherName === '' ||
        $mobile === '' ||
        !in_array($course, $allowedCourses, true)
    ) {
        $message = 'Please provide valid admission details.';
    } elseif (!preg_match('/^[0-9]{10}$/', $mobile)) {
        $message = 'Enter a valid 10-digit mobile number.';
    } else {
        $message = 'Admission form submitted successfully.';
    }
}
?>

<form method="post" action="">
    <label for="name">Student Name:</label>
    <input type="text" id="name" name="name" required>

    <br><br>

    <label for="father_name">Father's Name:</label>
    <input type="text" id="father_name" name="father_name" required>

    <br><br>

    <label for="mobile">Mobile Number:</label>
    <input
        type="tel"
        id="mobile"
        name="mobile"
        pattern="[0-9]{10}"
        maxlength="10"
        required
    >

    <br><br>

    <label for="course">Select Course:</label>
    <select id="course" name="course" required>
        <option value="">Choose Course</option>
        <option value="ADCA">ADCA</option>
        <option value="Web Development">Web Development</option>
        <option value="Tally Prime">Tally Prime</option>
    </select>

    <br><br>

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

<?php
if ($message !== '') {
    echo "<p>" .
        htmlspecialchars($message, ENT_QUOTES, 'UTF-8') .
        "</p>";
}
?>

The example checks the required fields, validates the mobile number format, and checks the selected course. A production admission system should save validated records using a database and prepared statements.

Practice Assignments
  1. Create a POST form that accepts a student's name.
  2. Create a form that accepts a name, email, and city.
  3. Build an addition calculator using POST.
  4. Create a registration form with a course dropdown.
  5. Display a selected radio-button value.
  6. Accept multiple selected courses using checkboxes.
  7. Validate a 10-digit mobile number on the server.
  8. Explain the differences between GET and POST.
  9. Create a student admission form with required-field validation.

🧠 Quick Quiz

1. Which PHP superglobal reads ordinary POST form fields?




2. Where is POST form data commonly sent?




3. Does POST automatically encrypt submitted data?