Introduction to GET and POST Methods in PHP
The backbone of communication on the World Wide Web is the Hypertext Transfer Protocol (HTTP), a client-server protocol that operates on a request-response model. Within HTTP, several methods exist designed to facilitate various interactions between clients and servers, including GET, POST, PUT, DELETE, HEAD, PATCH, CONNECT, TRACE, and OPTIONS. GET and POST are the most frequently utilized among these methods.
The GET and POST methods are the primary means for transmitting data between web pages and server-side scripts, such as those written in PHP. While both methods fulfill a similar purpose of exchanging information, they do so in distinct ways. Typically, developers use the GET method to retrieve data from a web server, while they prefer the POST method to submit sensitive data, upload files, and Perform actions that alter server-side information. The GET method can be used to retrieve data from a web server. You can submit data to a web server using the POST method. In this article, explore their functionalities, applications, and the advantages and disadvantages they offer in the realm of web development.
Table of Contents
What is the GET method?
Imagine you’re searching for a product on a website. The GET method comes into play here. When you enter a search term, it gets added to the URL as a query string (info following the “?”). The server receives this GET request and retrieves data based on your search criteria. In essence, GET excels at fetching data from the server. It’s also commonly used for triggering actions that don’t alter information on the server side, such as sorting or pagination functionalities.
The GET method is simpler and easier to use than the POST method. It is also idempotent. It means that if you make multiple identical requests, they will all result in the same outcome and have no negative impact. However, the GET method has a few disadvantages.
- First, the data sent by the GET method is visible in the URL, which can pose security risks.
- Second, the GET method can send up to 2048 data characters.
How does the GET method work?
In the GET method, the browser retrieves data from the server. You must mention the URL of the resource you want to retrieve. The browser then sends an empty body. Using the GET method, sending a form appends the data to the URL and transmits it to the server.
These are the steps:
- The user submits a form. The browser collects the form data and constructs the URL, appending data as query parameters.
- The browser builds URLs like http://example.com/page.php?param1=value1¶m2=value2, where page.php is the processing page, and param1=value1¶m2=value2 represents the form data.
- The browser sends HTTP GET requests to the server with that URL. The server extracts the query parameters.
- The server-side script receives the GET parameters in PHP using the $_GET.
- The server-side script processes the parameters. It does tasks like database operations, generating dynamic content, etc.
- The server generates responses, like rendering a webpage, returning JSON data, etc.
- Finally, the browser receives the response, renders it for the user, and interacts with it as needed.
In the event of success, the GET HTTP method returns the 200 OK response code. It typically returns a 400 (BAD REQUEST) or 404 (NOT FOUND) in an error case.
Example of GET method in PHP
Consider this simple example of how the GET method works in PHP. We need a form to fill out our name and email address. We can do this by using this HTML code:
index.html
<form action="getmethod.php" method="get">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
In this code, we can type name and email address. There is also a submit button to submit our values. We have also linked getmethod.php with the get method. Now, consider this code of getmethod.php.
getmethod.php
<?php
$name = $_GET['name'];
$email = $_GET['email'];
echo "Hello, $name! Your email is $email.";
?>
We print the name and email in this PHP code using the GET method.
You can save these files in the same folder and open them in VS code to execute them. You should have installed PHP on your machine. Open the command terminal in VS code and type the following command to execute the code on localhost.
php -S localhost:8080
Hit enter. It will open and run localhost on port 8080.
Output:
Explanation:
If you enter your name and email address, hit the submit button. The browser will construct a URL. For example, if we enter the name “Sammy” and the email address “[email protected],” Then hit the submit button.
The constructed URL by the browser will be
http://localhost:8000/getmethod.php?name=Sammy&email=Sammy%40educba.com.
The server-side script (getmethod.php) retrieves the name and email values using $_GET and generates a response accordingly.
It will display the output as “Hello, Sammy! Your email is [email protected],” as shown in the above GIF.
So, this is how the GET method works in PHP. You can access and display data using this method.
Note that you should not send sensitive data directly to a URL using the GET method because it shows everything in the URL, which can make the URL too long.
Advantages & Disadvantages of GET method
Advantages | Disadvantages |
The browser caches its requests and records them in the browser history. | It is limited data size to send, i.e., 2048 characters. |
You bookmark the page with the specific query string. | You should send sensitive information using GET because it appends passed information to the URL. |
It can retrieve information identified by the request URI. | Servers use this for string data types. It needs to be more suitable for images or Word documents. |
Developers use it when interacting with external services and APIs. | It is for requesting data only, not modification. |
It has good performance. | GET requests expose sensitive information through URLs, risking security breaches and making them vulnerable to tampering. |
What is the POST method?
GET’s partner in crime, the POST method, tackles a different yet crucial role: securely submitting data to the server. Imagine you’re filling out a login form or a survey. When you hit submit, that’s a POST method in action. The data you entered in the form is sent to the server for processing, often without being displayed in the URL. Compared to the GET method, the POST method is more secure. The URL does not display the data that was sent via the POST method. Data sent via the HTTP POST method is not limited in size. However, the POST method is more complex than the GET method.
How does the POST method work?
In the POST method, the browser sends the data to the server. It also creates or updates a resource on the server. This tool allows you to upload and submit
data on the server.
The HTTP POST method works in the following steps:
- A client sends a POST request specifying the resource URL and the data.
- The client creates a request object.
- The client encodes the submitted data.
- To the server is sent by the client’s request.
- The server processes the request.
- The server generates a response.
- The client receives the response from the server.
Finally, the browser receives a response from the server. It presents itself to the user and interacts with him as needed. Now, it can display updated content, handle form submissions, execute client-side scripts based on the response received, etc.
Example of POST method in PHP
Consider the following example. We want to create a form to submit user feedback. We will collect the user’s name, email, and feedback message. This data will be posted to the database using the POST technique. Consider this code of an HTML file. index.html
<!DOCTYPE html>
<html>
<head>
<title>Feedback Form</title>
</head>
<body>
<h2>Feedback Form</h2>
<form action="postmethod.php" method="post">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
Feedback: <textarea name="feedback"></textarea><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
This HTML code has a form to collect the user name, email, and feedback message. We have linked the form to postmethod.php using the POST method.
postmethod.php
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$feedback = $_POST['feedback'];
echo "<h2>Thank you for your feedback, $name!</h2>";
echo "<p>We received the following feedback from you:</p>";
echo "<p><strong>Email:</strong> $email</p>";
echo "<p><strong>Feedback:</strong> $feedback</p>";
?>
We retrieve the name, email, and feedback values in this PHP code using the $_POST method. After posting these values to the server, we will show a thank you message.
Now, you can save these files in the same folder. You need to open them in VS Code to execute them. You should have installed PHP on your machine. You need to open the command terminal in VS Code and type the following command to execute the code on localhost:
php -S localhost:8080
Hit enter. It will open and run localhost on port 8080.
Output:
Explanation:
Now, if you access http://localhost:8000/ in your browser, you will see the feedback form. You can complete the form and send it in. The browser will send the form data to postmethod.php using the POST method.
Once you enter these values and information, hit the submit button. For example, you will enter the name “Cillian,” email address “[email protected],” and a feedback message “EDUCBA is a great learning Platform.” Then, hit the submit button. The browser will not pass these values and information into the URL construction. So, the URL will be like this,
http://localhost:8000/postmethod.php
This URL does not show any information entered in the form. This is why you should use the POST instead of the GET method while passing sensitive information to the server.
It will post these values into the server, i.e., the database. Finally, we show a thank you message along with the feedback received. You can check the output message in the above GIF.
So, this is how the POST method works in PHP. You can securely submit form data without exposing it in the URL. Hence, it is suitable for sensitive information like passwords, personal details, etc.
Advantages & Disadvantages of POST method
Advantages | Disadvantages |
It is a secure method. | Since the POST method does not embed data in the URL, it is not possible to bookmark the page. |
It can send binary data, like images and Word documents. | You cannot store its request in the browser. |
The POST method allows you to send more extensive data for submission than the GET method because it doesn’t append data to the URL. So there is no issue. | It is less cacheable than the GET method. So, storing the results of a POST request and reusing them later is more complicated. |
You can send any data type, like string, numeric, binary, etc. | Its requests may perform slower than GET requests. This is because they have more steps to send and receive data. |
Differences between the GET method and POST method in PHP
Section | HTTP GET | HTTP POST |
Data Transmission | Data is sent as part of the URL query string. | Data is sent in the body of the HTTP request. |
Data Limitations | Limited by the maximum URL length. | Allows larger data transfers. |
Usage | Used for requesting data. | Used for creating and modifying data. |
Security | Less secure; data visible in the URL. | It is more secure; data is not exposed in the URL. |
Browser Behavior | The browser history stores requests. Cache memory stores requests, making it possible to bookmark them for later access. | The browser history does not store requests, and cache memory does not retain requests. So, Requests cannot be bookmarked or saved. |
Data Types | Only ASCII characters are allowed. | All types of data are allowed. |
Encoding Type | application/x-www-form-urlencoded. | application/x-www-form-urlencoded
or multipart/form-data, with multipart for binary data. |
Choosing the Right Method
You can choose a method based on a number of considerations. We have discussed some of them below.
1. Data Sensitivity
When data sensitivity matters, you should use the POST rather than the GET method.
2. Data Size
When passing extensive data, you should use the POST method instead of the GET method.
3. Caching
Store it locally in your browser if you want to cache the data. Then, choose the GET method.
4. Bookmarking
If you bookmark a request, use the GET method instead of the POST one.
5. Request Type
When requests are idempotent, the state of the server is not changed. You should use the GET method instead of the POST method.
You can choose the POST method over the GET method if you need more data security, data size, and server-side processing, i.e., modifying data.
Real-world Examples
There are various real-world examples of GET and POST methods in PHP. We have discussed some of them here.
- You can search for information on a website using the GET method.
- Using the POST method, you can register users on the website and submit their personal information, such as username, email, and password.
- You can upload files, like images, documents, etc., to a server using the POST method.
- You can checkout with sensitive information, like credit cards. These details are transmitted securely using POST requests to protect them from exposure.
Security Considerations
In PHP, GET requests are less secure than POST requests. GET requests to expose data in the URL. Therefore, anyone who can see the URL can also see the submitted data.
POST requests are more secure, as data is not visible in the URL. However, this still has security risks, like cross-site scripting (XSS) and cross-site request forgery (CSRF) attacks.
The $_REQUEST variable
In PHP, developers can utilize the $_REQUEST variable in place of $_GET, $_POST, and $_COOKIE variables to access data transmitted from client to server. You can access data submitted through the GET, POST, and cookie methods. Additionally, it proves useful in scenarios where you need to manage form data regardless of the method used to transmit it, whether it be GET or POST. You can replace $_REQUEST in place of $_GET and $_POST in getmethod.php and postmethod.php, respectively. The outputs and behavior do not change.
Conclusion
In web browsers, we communicate using client-server. HTTP is the communication protocol with different request-response methods in client-server systems. The GET and POST are the most used methods in PHP. GET is used to retrieve information from the server. POST is used to send and modify data on the server/database. GET has security concerns and cannot be used for sensitive data. POST is secure. There is an alternative, i.e., PHP’s $_REQUEST variable.
Frequently Asked Questions (FAQs)
Q1: Can you use both GET and POST methods in the same form?
Answer: Yes. You can use it, but you should understand the difference between them.
Q2: Are there any restrictions on the data types that can be sent using the POST method?
Answer: No. You can send various data types, like text, binary data (e.g., images, documents), and multimedia content.
Q3: Is there a limit to the number of parameters you can pass using the GET method?
Answer: While there is no strict limit on the number of parameters. However, you should keep the number of parameters reasonable to ensure compatibility and performance.
Recommended Articles
We hope that this EDUCBA information on “GET and POST Methods in PHP” was beneficial to you. You can view EDUCBA’s recommended articles for more information,