php
  1. php-form-get-post

PHP Form: Get Post

Syntax

To submit form data using GET method, use the $_GET global variable. To submit form data using POST method, use the $_POST global variable.

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  // Get form data using POST method
  $variable_name = $_POST["input_name"];
}
if ($_SERVER["REQUEST_METHOD"] == "GET") {
  // Get form data using GET method
  $variable_name = $_GET["input_name"];
}

Example

In this example, a simple form is created with one input field and a submit button. When the form is submitted, the data from the input field is displayed on the page.

<!DOCTYPE html>
<html>
<body>

<form action="" method="post">
  <label for="name">Name:</label><br>
  <input type="text" id="name" name="name"><br>
  <input type="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  // Get form data using POST method
  $name = $_POST["name"];
  echo "Hello, " . $name . "!";
}
?>

</body>
</html>

Output

When the form is submitted with the name "John", the output will be:

Hello, John!

Explanation

The form data is retrieved with the $_POST global variable. In this example, the name input field is assigned to a variable $name. The data from the input field is then displayed on the page using the echo statement.

Use

The $_GET and $_POST global variables are used to retrieve user input from a form. This data can be used to process user requests, or to store data in a database.

Important Points

  • $_GET should be used when the user input is used to retrieve data from the server
  • $_POST should be used when the user input is used to modify server data
  • Always sanitize user input to prevent security vulnerabilities

Summary

PHP forms can be submitted using the GET or POST method. The $_GET and $_POST global variables are used to retrieve form data in PHP. Sanitizing user input is important to prevent security vulnerabilities.

Published on: