Forms are a critical part of the web. They allow websites to collect information from their users and then process it to perform actions. For example, when you submit a username and password combination, a website can then log you in.
If you need a refresher on forms, check out our HTML lesson on it. In this lesson, we'll learn how to create forms, the different ways to submit data, and how to handle and validate that data.
The GET method is pretty simple, and you've seen it before. The data is sent in the URL itself. Here's an example from Google:
The data in
is found here:
The GET method uses key-value pairs and in this case, the
q, standing for query, is the key, and
sabe.io is the value. This is how Google knows what you searched in the box.
<form action="/search.php" method="GET"> <input type="text" name="query" /> <input type="submit" /> </form>
<?php echo($_GET['query']); ?>
Notice the URL? When you hit submit, the browser knows to automatically take all the data in the form and send it to whatever is the
action, in this case, to
search.php can handle the request itself.
In PHP, you read all GET variables using the
$_GET array. Since the value of the
name attribute was
query, that is the same value used to access the data. Since we are just calling
echo() with that data, that is why we see our query on the page.
Here are some more information about using the GET method:
- Using the GET method allows you to bookmark a URL since the data is self-contained within the URL itself.
- Because the data is included in the URL, it is not recommended that you pass in sensitive data, since it can be easily read.
- There is a limit of 1024 characters.
- You technically do not need a form to send the data to the server. Simply enter new data right into the URL and hit enter!
The POST method works almost in the exact same way except that the data is sent in the request made to the server and not the URL. That means that the data isn't visible in the URL like a GET request. It otherwise works exactly the same. Here is the same implementation of the earlier example using a POST request.
<form action="/search.php" method="POST"> <input type="text" name="query" /> <input type="submit" /> </form>
<?php echo($_POST['query']); ?>
In pretty much every single way, this example is the same as before. Since the form was set to use the
POST method, the data was sent with the request. You can then access those POST variables using
$_POST and then passing in the name of the piece of data you're trying to access.
Here are some more information about using the POST method:
- It is recommended for use with more sensitive information since the data is never shown in the URL itself.
- You can post more than just text including images and video.
- You cannot bookmark a page that requires POST data since the data isn't there.
Many websites and applications depend on forms so becoming familiar with them is very useful if you want to build your own feature-rich website!