What is $_POST in PHP: Simple Explanation and Usage
$_POST in PHP is a special array that holds data sent from a web form using the HTTP POST method. It allows you to access user input securely on the server side after a form submission.How It Works
Imagine you fill out a form on a website, like signing up or sending a message. When you press submit, your browser sends the information to the server. If the form uses the POST method, PHP collects this data and stores it in a special container called $_POST.
This container is like a labeled box where each piece of information is stored with a name (the form field's name). You can then open this box in your PHP code and use the data to do things like save it to a database or send an email.
Example
This example shows a simple HTML form and a PHP script that reads the submitted data using $_POST.
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $name = $_POST['name'] ?? 'Guest'; $email = $_POST['email'] ?? 'No email provided'; echo "Hello, $name! Your email is $email."; } else { ?> <form method="post" action=""> Name: <input type="text" name="name"><br> Email: <input type="email" name="email"><br> <input type="submit" value="Submit"> </form> <?php } ?>
When to Use
Use $_POST when you want to send data from a user to your server securely and without showing it in the web address. This is common for login forms, contact forms, or any time you need to send sensitive or large amounts of data.
Because POST data is not visible in the URL, it is better for privacy and security compared to GET requests. It also allows sending more data than GET.
Key Points
- $_POST is a PHP superglobal array holding form data sent via HTTP POST.
- It helps you access user input securely on the server side.
- Data sent by POST is not visible in the URL, making it more private.
- Always validate and sanitize
$_POSTdata to keep your site safe.
Key Takeaways
$_POST holds data sent from HTML forms using the POST method.$_POST to securely receive user input on the server.$_POST data before using it.