PHP: HTTP GET and POST Methods

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

714 views
d

By. Jacob

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:

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

Tell us what you think:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials