Share via:

PHP: HTTP GET and POST Methods

Learn how to use the HTTP POST and GET methods in your HTML forms.

35 views

Edited: 2019-11-03 06:03

The HTTP GET and POST methods is used to communicate over the Hypertext Transfer Protocol (HTTP) from web browsers (clients).

The methods can also be used in software on the server-side. When this is done, it usually happens to fetch data from external web resources. Most programming and scripting languages has ways to send HTTP requests for such purposes.

When submitting a HTML form from a browser, you would often be using the POST submission method, since this has several advantages compared to using the GET method. To mention a few:

  • POST is not restrained by URL limitations, since data is posted rather than "requested".
  • Posted data will quietly be submitted, without revealing it in the address bar.
  • Posted data will not show up in server log files as part of requested URLs.

However, one does not rule out the other. For example, you could have a HTML form submitted with the POST method, and still use GET parameters in the action URL. This is perfectly valid, and sometimes even desirable.

GET and POST in a HTML form

By default, a HTML form will be submitted using GET, but we can change this using the method attribute.

The below HTML form is submitting data using the POST method to a server-sided PHP script, once the script receives the submitted data, it will attempt to validate it and output it to the browser for you to see.

<form action="/Examples/submission_handler.php?action=edit" method="POST">
  <label>First name:</label>
  <input type="text" name="firstname" value="Rasmus">

  <label>Last name:</label>
  <input type="text" name="lastname" value="Lerdorf">

  <input type="submit" value="Submit">
</form>

You can try to hit the submit button in the below HTML form to test and see what happens:

Which is better

In most circumstances, you will probably want to use the POST method to submit your forms. This is because POST is more secure when submitting sensitive data.

Login forms should always be submitted using the POST method. This avoids accidentally logging users passwords in clear text in your server log files.

However, in some cases it actually makes sense to use a combination of GET and POST. Your form will still be submitted using the POST type, but the URL parameters in the action URL will still be accessible. You can test how this works by submitting the form from earlier.

Links

  1. PHP HTTP Requests

Comments