How do you retrieve data from a form in PHP?
In PHP, you retrieve data from a form using the $_POST or $_GET superglobal arrays, depending on the form's method. Here's a basic example for each method:
Using $_POST:
If your form uses the POST method, you retrieve data like this:
HTML Form:
<form method="post" action="process_form.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<input type="submit" value="Submit">
</form>
PHP Script (process_form.php):
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
echo "Name: " . htmlspecialchars($name);
}
?>
Using $_GET:
If your form uses the GET method, you retrieve data like this:
HTML Form:
<form method="get" action="process_form.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<input type="submit" value="Submit">
</form>
PHP Script (process_form.php):
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$name = $_GET['name'];
echo "Name: " . htmlspecialchars($name);
}
?>
Key Points:
- Use
$_POSTfor data sent via POST (which hides data from the URL). - Use
$_GETfor data sent via GET (which appends data to the URL). - Always sanitize user input using functions like
htmlspecialchars()to avoid XSS (Cross-Site Scripting) attacks.
Feel free to ask if you need more details on form handling or anything else!
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
