What is the use of "$_GET" and "$_POST" in PHP? How are they different?

In PHP, $_GET and $_POST are superglobal arrays used to collect form data sent with both the GET and POST methods, respectively.

  1. $_GET: This array is used to collect form data sent via the HTTP GET method. It retrieves variables from the query string in the URL. Data sent using GET method is visible in the URL, as it appends key-value pairs to the URL after a question mark (?). It is commonly used for submitting small amounts of non-sensitive data, such as search queries or filtering options. Example: $_GET['name'] retrieves the value of the name parameter from the URL.

  2. $_POST: This array is used to collect form data sent via the HTTP POST method. It retrieves variables from the request body of an HTTP POST request. Unlike GET data, POST data is not visible in the URL, making it more suitable for handling sensitive or large amounts of data, such as login credentials or form submissions with large text fields. Example: $_POST['email'] retrieves the value of the email field submitted via a form with POST method.

Difference:

  • The main difference between $_GET and $_POST is the way data is sent and retrieved. $_GET retrieves data from the query string in the URL, while $_POST retrieves data from the request body of an HTTP POST request.

  • Data sent using GET method is limited by the maximum length of a URL, while POST method allows for larger amounts of data to be transmitted.

  • Data sent via GET method is visible in the URL, while POST data is not.

  • GET requests can be bookmarked and cached, while POST requests are not bookmarked or cached by default.