Day 10Understanding HTTP Methods in PHP: GET, POST, PUT, DELETE

Day 10Understanding HTTP Methods in PHP: GET, POST, PUT, DELETE
Day 10Understanding HTTP Methods in PHP: GET, POST, PUT, DELETE

In web development, HTTP methods are essential for creating a seamless interaction between the client and server. These methods represent actions performed on resources, often through APIs or forms. In this article, we’ll cover the four most commonly used HTTP methods — GET, POST, PUT, and DELETE — explaining their purposes, usage, and implementation in PHP.


1. GET Method

The GET method is used to retrieve data from a server. It appends the data to the URL as query parameters, making it visible to the user. This method is idempotent, meaning multiple requests will not cause a change in the server's state.

Key Features:

  • Data is sent as part of the URL query string.
  • Suitable for non-sensitive data and operations that don’t alter server state.
  • Limited data size (browser URL length restrictions).

PHP Example:

HTML Form:

html
<form action="handle_get.php" method="GET"> <label for="search">Search:</label> <input type="text" name="search" id="search"> <button type="submit">Submit</button> </form>

PHP Script (handle_get.php):

php
<?php if (isset($_GET['search'])) { $searchTerm = htmlspecialchars($_GET['search']); echo "You searched for: " . $searchTerm; } else { echo "No search term provided."; } ?>

Use Case:

  • Search functionality where the query can be bookmarked and shared.

2. POST Method

The POST method is used to send data to the server for processing, often when creating or updating resources. Unlike GET, data is sent in the request body, making it suitable for sensitive information.

Key Features:

  • Data is not visible in the URL.
  • Used for creating or updating data on the server.
  • No data size limitations.

PHP Example:

HTML Form:

html
<form action="handle_post.php" method="POST"> <label for="username">Username:</label> <input type="text" name="username" id="username"> <label for="password">Password:</label> <input type="password" name="password" id="password"> <button type="submit">Login</button> </form>

PHP Script (handle_post.php):

php
<?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $username = htmlspecialchars($_POST['username']); $password = htmlspecialchars($_POST['password']); echo "Username: $username<br>Password: $password"; } else { echo "Invalid request."; } ?>

Use Case:

  • Submitting forms with sensitive data, such as login or registration.

3. PUT Method

The PUT method is used to update existing data on the server. It is commonly utilized in RESTful APIs. While HTML forms do not support PUT directly, you can simulate it using JavaScript or HTTP clients like Postman.

Key Features:

  • Updates existing resources.
  • Requires the client to provide the full resource data.

PHP Example:

Simulating a PUT Request:

php
<?php parse_str(file_get_contents("php://input"), $_PUT); if ($_SERVER['REQUEST_METHOD'] == 'PUT') { $id = htmlspecialchars($_PUT['id']); $newData = htmlspecialchars($_PUT['data']); echo "Updated resource ID: $id with data: $newData"; } else { echo "Invalid request."; } ?>

Making a PUT Request (Using cURL in PHP):

php
$data = ['id' => 1, 'data' => 'Updated Value']; $ch = curl_init('http://example.com/handle_put.php'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); echo $response;

Use Case:

  • Updating user profiles or other records in a database.

4. DELETE Method

The DELETE method is used to delete a resource on the server. Like PUT, it is not directly supported by HTML forms but can be used via JavaScript or HTTP clients.

Key Features:

  • Deletes a resource on the server.
  • Idempotent — repeated requests yield the same result.

PHP Example:

Simulating a DELETE Request:

php

<?php parse_str(file_get_contents("php://input"), $_DELETE); if ($_SERVER['REQUEST_METHOD'] == 'DELETE') { $id = htmlspecialchars($_DELETE['id']); echo "Deleted resource with ID: $id"; } else { echo "Invalid request."; } ?>

Making a DELETE Request (Using cURL in PHP):

php
$data = ['id' => 1]; $ch = curl_init('http://example.com/handle_delete.php'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); echo $response;

Use Case:

  • Deleting records, such as user accounts or posts.

Comparison of GET, POST, PUT, and DELETE

FeatureGETPOSTPUTDELETE
VisibilityData in URL.Data in request body.Data in request body.Data in request body.
PurposeRetrieve data.Send data to create resources.Update existing resources.Delete resources.
IdempotentYes.No.Yes.Yes.
CachingCan be cached.Not cached.Not cached.Not cached.
Data SizeLimited by URL length.No significant limits.No significant limits.No significant limits.
SecurityLess secure (visible data).More secure (hidden data).Secure (hidden data).Secure (hidden data).

Final Summary

Understanding and using HTTP methods effectively is crucial for building robust web applications. Here's a summary of when to use each method:

  • GET: For retrieving data or actions that do not alter the server's state.
  • POST: For sending sensitive or large amounts of data and creating resources.
  • PUT: For updating existing resources on the server.
  • DELETE: For removing resources from the server.

Each method has its unique use cases and characteristics. By leveraging these methods appropriately, you can create efficient and secure client-server interactions.

Blog categories