PHP Superglobal - $_POST (With Examples)

By Shahnail Khan Last updated : December 14, 2023

PHP $_POST

$_POST is a PHP superglobal variable that is used to collect form data after submitting an HTML form with the method set to POST. It's an associative array, meaning it stores data in key-value pairs, making it easy to retrieve user input.

Syntax of PHP $_ POST

The syntax for accessing and using $_POST is:

$value = $_POST['fieldname'];

Here,

  • $value: This is a variable where you store the value you get from the form field.
  • $_POST: It's like a container that holds all the data sent from an HTML form using the POST method.
  • 'fieldname': Replace this with the actual name of the form field you want to get data from.

Example of PHP $_POST

Let's take an example to understand how $_POST works.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title of the page!</title>
</head>
<body>
    <h2>Sign in</h2>
    <form method="post">
        <label for="username">Username:</label>
        <input type="text" name="username" id="username" required>
        <br>
        <label for="password">Password:</label>
        <input type="password" name="password" id="password" required>
        <br>
        <input type="submit" value="Submit">
    </form>

    <?php
    // Check if form is submitted using the POST method
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Retrieve values from the form using $_POST
        $username = $_POST['username'];
        $password = $_POST['password'];

        // Simple login check (replace this with your actual authentication logic)
        if ($username === 'user123' && $password === 'pass456') {
            echo "<h1>Login successful! Welcome, $username!</h1>";
        } else {
            echo "<p>Login failed. Please check your username and password.</p>";
        }
    }
    ?>
</body>
</html>

Output

Without adding the username and password, this is how the output looks:

superglobal post example output 1

Once you have filled in all the necessary details, you will get the output something like this:

superglobal post example output 2

Explanation

  • The HTML part contains a form with two input fields (username and password) and a submit button.
  • The PHP part checks if the form is submitted using the POST method (if ($_SERVER['REQUEST_METHOD'] === 'POST')).
  • It retrieves the values entered in the form fields using $_POST ($username = $_POST['username'] and $password = $_POST['password']).
  • It displays a message based on the login result.

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.