How to Submit Form Using POST in PHP: Simple Guide
To submit a form using
POST in PHP, set the form's method attribute to post and use $_POST in PHP to access submitted data. The form data is sent securely in the request body, not visible in the URL.Syntax
Use the <form> tag with method="post" to send data. In PHP, access the data with $_POST['field_name'].
- method="post": Sends form data in the HTTP request body.
- action="file.php": The PHP file that processes the form.
- $_POST: PHP superglobal array holding submitted data.
php
<form method="post" action="process.php"> <input type="text" name="username"> <input type="submit" value="Submit"> </form> <?php // Access submitted data $username = $_POST['username'] ?? ''; ?>
Example
This example shows a simple form that submits a username using POST. The PHP script then displays the submitted username.
php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>POST Form Example</title> </head> <body> <form method="post" action=""> <label for="username">Username:</label> <input type="text" id="username" name="username" required> <input type="submit" value="Submit"> </form> <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $username = htmlspecialchars($_POST['username']); echo "<p>Hello, " . $username . "!</p>"; } ?> </body> </html>
Output
Hello, Alice!
Common Pitfalls
- Forgetting to set
method="post"causes data to be sent via GET. - Not checking
$_SERVER['REQUEST_METHOD']can cause errors when page loads without form submission. - Not sanitizing input can lead to security issues like XSS.
- Using
$_POSTwithout verifying keys may cause undefined index warnings.
php
<?php // Wrong: No method specified, defaults to GET ?> <form action=""> <input name="data"> <input type="submit"> </form> <?php // Right: Use POST and check request method if ($_SERVER['REQUEST_METHOD'] === 'POST') { $data = htmlspecialchars($_POST['data'] ?? ''); echo $data; } ?>
Quick Reference
Remember these key points when submitting forms with POST in PHP:
- Set
method="post"in your form tag. - Use
$_POST['field_name']to get submitted data. - Check
$_SERVER['REQUEST_METHOD'] === 'POST'before processing. - Sanitize inputs with
htmlspecialchars()or similar.
Key Takeaways
Always set
method="post" in your form to send data securely.Access submitted data in PHP using the
$_POST array.Check the request method with
$_SERVER['REQUEST_METHOD'] before processing form data.Sanitize user input to prevent security risks like cross-site scripting.
Avoid undefined index errors by verifying keys exist in
$_POST.