How to Get Form Data in PHP: Simple Guide
In PHP, you get form data using the
$_GET or $_POST superglobal arrays depending on the form's method. Use $_GET['fieldname'] for data sent via URL and $_POST['fieldname'] for data sent via HTTP POST.Syntax
To get form data in PHP, use the superglobal arrays $_GET or $_POST. These arrays hold key-value pairs where keys are the form field names.
- $_GET['fieldname']: Retrieves data sent via URL parameters (GET method).
- $_POST['fieldname']: Retrieves data sent via HTTP POST method.
Replace fieldname with the actual name attribute of your form input.
php
<?php // Access form data sent by GET method $name = $_GET['name']; // Access form data sent by POST method $email = $_POST['email']; ?>
Example
This example shows a simple HTML form that sends data using POST method and a PHP script that receives and displays the submitted data.
php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Form Data Example</title> </head> <body> <form method="post" action=""> <label for="username">Username:</label> <input type="text" id="username" name="username" required> <br><br> <label for="age">Age:</label> <input type="number" id="age" name="age" required> <br><br> <button type="submit">Submit</button> </form> <?php if ($_SERVER["REQUEST_METHOD"] === "POST") { $username = $_POST['username']; $age = $_POST['age']; echo "<p>Hello, <strong>" . htmlspecialchars($username) . "</strong>. You are <strong>" . htmlspecialchars($age) . "</strong> years old.</p>"; } ?> </body> </html>
Output
Hello, <strong>John</strong>. You are <strong>30</strong> years old.
Common Pitfalls
Common mistakes when getting form data in PHP include:
- Using the wrong superglobal (
$_GETvs$_POST) depending on the form method. - Not checking if the form data exists before accessing it, which can cause errors.
- Not sanitizing or escaping user input, which can lead to security issues.
Always check if the data is set using isset() and sanitize output with htmlspecialchars().
php
<?php // Wrong way: Accessing POST data without checking // $name = $_POST['name']; // May cause error if form not submitted // Right way: Check if data exists first if (isset($_POST['name'])) { $name = htmlspecialchars($_POST['name']); } else { $name = ''; } ?>
Quick Reference
Summary tips for getting form data in PHP:
- Use
$_GETfor forms withmethod="get". - Use
$_POSTfor forms withmethod="post". - Always check if the form data exists with
isset(). - Sanitize user input before output to avoid security risks.
- Use
$_SERVER['REQUEST_METHOD']to detect form submission method.
Key Takeaways
Use $_GET or $_POST to access form data depending on the form's method attribute.
Always check if form data exists with isset() before using it.
Sanitize user input with htmlspecialchars() to prevent security issues.
Use $_SERVER['REQUEST_METHOD'] to detect how the form was submitted.
Match the superglobal to the form method: GET for URL parameters, POST for form body.