Handling HTTP Methods

(GET and POST) and Forms

PHP supports the HTTP GET and POST methods, and it provides a way to handle data submitted via HTML forms.

HTTP GET

The GET method is used to retrieve information from the given server using a given URI. The information is encoded and appended to the URL as a query string. Here is an example of how PHP handles GET data:

<?php
echo "Hi " . htmlspecialchars($_GET['name']) . "!";
?>

In the above example, $_GET is an associative array containing all GET variables that are passed via the URL. htmlspecialchars is used to prevent cross-site scripting (XSS) attacks.

HTTP POST

The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING. Here is how PHP handles POST data:

<?php
echo "Hi " . htmlspecialchars($_POST['name']) . "!";
?>

In this example, $_POST is an associative array of variables passed to the current script via the HTTP POST method.

Handling HTML Forms

PHP provides a way to handle HTML form data. You can use the $_POST or $_GET array to access the data. Here's a simple form processing script:

<?php
$name = $email = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = test_input($_POST["name"]);
  $email = test_input($_POST["email"]);
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

In the above script, $_SERVER["REQUEST_METHOD"] is used to retrieve the request method. test_input is a custom function that cleans up the input data to prevent injections.

Understanding how to handle HTTP methods and forms is fundamental to creating interactive web applications with PHP.

Last updated