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
$_POST
for data sent via POST (which hides data from the URL). - Use
$_GET
for 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!
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.