0
0
PhpHow-ToBeginner · 3 min read

How to Submit Form Using GET in PHP: Simple Guide

To submit a form using GET in PHP, set the form's method attribute to "get". When the form is submitted, data is sent via the URL query string and accessed in PHP using the $_GET superglobal array.
📐

Syntax

The form tag uses the method="get" attribute to send data via URL. The action attribute specifies the PHP file that will process the data. In PHP, use $_GET['field_name'] to access submitted values.

php
<form action="process.php" method="get">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name">
  <input type="submit" value="Submit">
</form>

<?php
// Access submitted data
if (isset($_GET['name'])) {
    $name = $_GET['name'];
    echo "Hello, " . htmlspecialchars($name) . "!";
}
?>
💻

Example

This example shows a simple form that submits a user's name using GET. The PHP code then reads the name from the URL and displays a greeting.

php
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>GET Form Example</title>
</head>
<body>
  <form action="" method="get">
    <label for="username">Enter your name:</label>
    <input type="text" id="username" name="username">
    <input type="submit" value="Send">
  </form>

  <?php
  if (isset($_GET['username']) && $_GET['username'] !== '') {
      $user = htmlspecialchars($_GET['username']);
      echo "<p>Hello, $user!</p>";
  }
  ?>
</body>
</html>
Output
Hello, Alice!
⚠️

Common Pitfalls

  • Not setting method="get" causes the form to default to GET, but some browsers may default to POST, which may confuse data retrieval.
  • Using $_POST instead of $_GET when the form uses GET will result in empty data.
  • Not sanitizing user input can lead to security issues; always use htmlspecialchars() when displaying data.
  • GET method appends data to the URL, so avoid sending sensitive information.
php
<!-- Wrong: method POST but trying to read $_GET -->
<form method="post">
  <input name="email">
  <input type="submit">
</form>

<?php
// This will not work if form uses POST
if (isset($_GET['email'])) {
  echo $_GET['email'];
}

// Correct way:
// Use method="get" in form or read from $_POST if method="post"
?>
📊

Quick Reference

Form attribute: method="get" sends data via URL query string.
Access data in PHP: Use $_GET['field_name'].
Use GET when: You want data visible in URL, like search queries.
Avoid GET when: Sending passwords or large data.

Key Takeaways

Set the form's method attribute to "get" to submit data via URL.
Access submitted data in PHP using the $_GET superglobal array.
Always sanitize user input before displaying it to avoid security risks.
GET method appends data to the URL, so do not use it for sensitive information.
Use GET for simple, non-sensitive data like search terms or filters.