Web browsers communicate with servers primarily using two HTTP (Hypertext Transfer Protocol) methods: GET and POST. Both methods handle data differently and come with distinct advantages and disadvantages, as outlined below.
In the GET method, data is transmitted as URL parameters, typically in the form of name-value pairs separated by ampersands (&
). A typical URL with GET data looks like this:
In this URL, the bold parts represent the GET parameters, while the italic parts denote their corresponding values. Multiple parameter=value
pairs can be included in the URL by concatenating them with ampersands (&
). The GET method is suitable only for transmitting simple text data.
PHP provides the $_GET
superglobal variable to access all information sent via URL or submitted through an HTML form using method="get"
.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of PHP GET method</title>
</head>
<body>
<?php
if(isset($_GET["name"])){
echo "<p>Hi, " . $_GET["name"] . "</p>";
}
?>
<form method="get" action="<?php echo $_SERVER["PHP_SELF"];?>">
<label for="inputName">Name:</label>
<input type="text" name="name" id="inputName">
<input type="submit" value="Submit">
</form>
</body>
In the POST method, data is sent to the server as a package in a separate communication with the processing script. Unlike GET, data sent through POST method is not visible in the URL.
Similar to $_GET
, PHP provides another superglobal variable $_POST
to access all information sent via POST method or submitted through an HTML form using method="post"
.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of PHP POST method</title>
</head>
<body>
<?php
if(isset($_POST["name"])){
echo "<p>Hi, " . $_POST["name"] . "</p>";
}
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
<label for="inputName">Name:</label>
<input type="text" name="name" id="inputName">
<input type="submit" value="Submit">
</form>
</body>
PHP includes another superglobal variable $_REQUEST
that consolidates the values from $_GET
, $_POST
, and $_COOKIE
variables.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of PHP $_REQUEST variable</title>
</head>
<body>
<?php
if(isset($_REQUEST["name"])){
echo "<p>Hi, " . $_REQUEST["name"] . "</p>";
}
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
<label for="inputName">Name:</label>
<input type="text" name="name" id="inputName">
<input type="submit" value="Submit">
</form>
</body>
You'll delve deeper into PHP cookies and form handling in the advanced section.
Note: The superglobal variables $_GET
, $_POST
, and $_REQUEST
are predefined variables that remain accessible in all parts of a script.