DEV Community

Cover image for How to Make DELETE Requests Using the curl_init() Function in PHP
Emmanuel Mumba
Emmanuel Mumba

Posted on

How to Make DELETE Requests Using the curl_init() Function in PHP

The curl_init() function within the cURL library allows developers to programmatically send HTTP DELETE requests, making it easier to remove resources from a server with just a few lines of code. This function provides a flexible way to interact with RESTful APIs and manage data deletion processes.

The cURL project, formally known as "Client for URLs," provides developers with a powerful set of tools for managing data transfers across networks. It functions in two main modes: a user-friendly command-line interface for simple operations and a versatile library, ideal for embedding within software development projects to enable more complex interactions. This dual functionality makes cURL an essential tool for working with APIs and handling HTTP requests like DELETE.

Enhance your cURL API design and testing with Apidog, a powerful tool that covers every stage of the API lifecycle. With Apidog, you can easily build, debug, mock, and document your cURL APIs, all in one platform

Formal Definition of curl_init()

According to the official PHP documentation, the curl_init() function initializes a cURL session and returns a handle that can be used with other cURL functions such as curl_setopt(), curl_exec(), and curl_close().

Parameters Involved

  • url: If a URL is provided as an argument to curl_init(), the CURLOPT_URL option will be set to that value. Alternatively, this option can be set manually using the curl_setopt() function.

Note that the file protocol is automatically disabled by cURL if the open_basedir option is enabled in PHP.

Return Values

Upon success, curl_init() returns a cURL handle, which is used to configure and execute the request. In case of an error, it returns false.

What is a DELETE Request?

A DELETE request is an HTTP method that instructs a server to remove or delete a specified resource. This resource could range from files to database entries or any other data that the server is responsible for managing. The DELETE method is often used when an application needs to remove data permanently from the server.

How DELETE Requests Function

Here’s a detailed look at how DELETE requests work:

Step 1 - Client Initiation

A client, which could be a web browser or a software application, initiates the process by sending a DELETE request to the server.

Step 2 - Specifying the Resource

The DELETE request contains a Uniform Resource Identifier (URI) that indicates the specific resource on the server intended for removal.

Step 3 - Server Processing

When the server receives the DELETE request, it processes the request and, if everything is in order, deletes the specified resource.

Step 4 - Sending a Response

After processing, the server sends back a response code to the client, which indicates the result of the deletion attempt. Common success response codes include:

  • 200 (OK): The resource was deleted successfully.
  • 202 (Accepted): The deletion request has been accepted but is still being processed.
  • 204 (No Content): The deletion was successful, but there is no additional information to return.

Important Considerations About DELETE Requests

  • Idempotent Behavior: Repeating the same DELETE request should yield the same result, meaning the resource is only deleted once.

  • No Immediate Guarantees: Even with a successful response code, the actual deletion of the resource may not occur immediately due to server-side handling or policies.

  • Permanent Removal: Typically, DELETE requests result in the permanent deletion of resources, unlike modification requests that may retain the original data.


Code Examples for Making DELETE Requests with the curl_init() Function

Example 1 - Basic DELETE Request

<?php
// Initialize a new cURL session
$ch = curl_init();

// Specify the URL of the resource to be deleted
curl_setopt($ch, CURLOPT_URL, "https://example.com/resource/123");

// Set the request method to DELETE
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");

// Execute the cURL session
$response = curl_exec($ch);

// Handle any potential errors
if(curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}

// Close the cURL session to free up resources
curl_close($ch);
?>
Enter fullscreen mode Exit fullscreen mode

Code Explanation

  1. Setting the Target URL: The target URL for the DELETE request is defined.
  2. Initialize cURL: curl_init($url) initializes the cURL handle for making requests.
  3. Specify the Request Method: curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE") sets the request method to "DELETE."
  4. Capture the Response: curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ensures the response is returned as a string rather than being directly output.
  5. Execute the Request: $response = curl_exec($ch) executes the DELETE request and stores the response.
  6. Retrieve the HTTP Response Code: $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE) retrieves the HTTP response code.
  7. Close the cURL Handle: The cURL handle is closed using curl_close($ch).
  8. Response Code Check: The code checks the response code, with a 200 status indicating a successful deletion.

Example 2 - DELETE Request with Authentication

<?php
$url = "https://api.example.com/protected/resources/456"; // Replace with your URL
$username = "your_username";
$password = "your_password";

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);  // Set credentials

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

// ... (check response code and handle accordingly)
?>
Enter fullscreen mode Exit fullscreen mode

Code Explanation

  1. Define URL and Credentials: The URL and authentication credentials are specified.
  2. Follow Previous Structure: The code structure is consistent with the previous example, incorporating authentication.
  3. Set Authentication: curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password) sets the username and password for basic authentication.

Example 3 - DELETE Request with JSON Payload (Python)

import json
import curl

url = "https://api.example.com/data"
data = {"id": 789}  # Replace with your data

headers = {"Content-Type": "application/json"}

response = curl.easy.request(
    url,
    custom_request="DELETE",
    data=json.dumps(data).encode("utf-8"),  # Encode data as JSON bytes
    headers=headers
)

if response.status_code == 200:
    print("Resource deleted successfully!")
else:
    print(f"Error deleting resource: {response.status_code}")
Enter fullscreen mode Exit fullscreen mode

Code Explanation

  1. Import Libraries: Necessary libraries are imported, and the URL and data object are defined.
  2. Set Content-Type Header: The Content-Type header is set to indicate that the payload is in JSON format.
  3. Perform the DELETE Request: curl.easy.request performs the request, using the specified parameters:
    • url: The target URL.
    • custom_request: Set to "DELETE."
    • data: The JSON data, encoded as bytes.
    • headers: A dictionary containing the Content-Type header.
  4. Check Response Status: The response status code is checked for success (200).

Note to Remember

Please ensure the code samples provided are adapted to fit your specific application's needs, as they are simplified for demonstration purposes.

For more details, refer to the official documentation at: PHP cURL Documentation.

Apidog - Design cURL API to Perfection

Apidog - Design cURL API to Perfection

If you're looking for a comprehensive and streamlined approach to API development, Apidog is a platform worth considering. It offers a complete suite of tools tailored for every stage of the API lifecycle—from design to documentation. With Apidog, developers can craft, debug, and optimize their cURL API workflows seamlessly, ensuring efficient and high-quality development.

Import cURL APIs to Apidog

Apidog allows you to import your cURL APIs directly, making it easier to manage, test, and optimize your API workflows. Whether you're working with existing cURL scripts or creating new ones, Apidog enables a seamless integration process that simplifies debugging and collaboration within your development environment.

Apidog enables a seamless integration

Importing cURL Commands to Apidog

Apidog provides a simple process for users to import cURL commands. To get started in an empty project, click the purple + button located in the top left corner of the Apidog interface. From the dropdown menu, select Import cURL. This feature allows you to quickly bring in your cURL commands, making it easier to manage and refine your API requests within Apidog's robust platform.

Importing cURL Commands to Apidog

Copy and paste your cURL command into the provided text box that appears on your screen after selecting the Import cURL option in Apidog. This will automatically transform your cURL command into a request format that you can manage, test, and modify directly within the Apidog platform.

Importing cURL Commands to Apidog

If successful, you will now be able to see your cURL command transformed into an API request format within Apidog. This allows you to easily interact with, test, and modify the request as part of your API development process.

Generate PHP Code for cURL API with Apidog

No prior experience with PHP? No problem! Apidog's code generation feature makes it easy. With this tool, you can automatically generate PHP code for your cURL API requests. Apidog also offers code frameworks for several other programming languages, making it an excellent choice for developers seeking to streamline their development process without having to write code from scratch.

Generate PHP Code for cURL API with Apidog

First, find the </> Generate Code button on any API or request within Apidog. From the drop-down menu, choose Generate Client Code to access pre-built code snippets. This option will allow you to generate client-side code, including PHP, for your cURL API requests.

Generate PHP Code for cURL API with Apidog

Conclusion

The curl_init() function in cURL offers developers a powerful method for programmatically handling data deletion through HTTP DELETE requests. This enables the removal of resources on remote servers directly from applications, making it an essential tool for data management, system synchronization, and compliance with data governance policies.

Additionally, cURL’s flexibility allows for various DELETE request scenarios, ranging from simple operations to more advanced use cases involving authentication and complex payloads. By harnessing cURL's capabilities, developers can achieve efficient and precise control over resource deletion, improving the effectiveness of their software solutions.

Top comments (0)