Current Location: Home> Latest Articles> Build a middleware interceptor that supports curl_share

Build a middleware interceptor that supports curl_share

M66 2025-06-06

In PHP, curl_share_init is a very useful function. It allows multiple cURL requests to share the same resources, such as sessions, cookies, or files, etc., which can effectively reduce the overhead of repeated requests for resources and improve performance. In actual applications, we may need to centrally manage, configure or intercept multiple requests, and the middleware interceptor is particularly important.

This article will explain how to build a middleware interceptor that supports curl_share_init , and help you better understand this process with practical examples.

What is a middleware interceptor?

A middleware interceptor is a component used to intercept requests and responses, which can perform certain operations before the request enters and after the response leaves. Typically, they are used to log logs, handle authentication, cache control, request header addition, response formatting, etc.

In our case, the interceptor would do some additional processing before or after the cURL request occurred. For middleware that supports curl_share_init , our goal is to ensure that one session resource can be shared across multiple cURL requests, thus avoiding the initialization of a new cURL session every time.

Build steps

1. Create a middleware basic framework

We can create a middleware class that is specifically used to handle all cURL request interception. This class will provide some basic initialization and resource management functions.

 class CurlMiddleware
{
    private $shareHandle;

    public function __construct()
    {
        // Initialize shared resources
        $this->shareHandle = curl_share_init();
    }

    public function __destruct()
    {
        // Destroy shared resources
        if ($this->shareHandle) {
            curl_share_close($this->shareHandle);
        }
    }

    public function handleRequest($url, $options = [])
    {
        // set up cURL Share resources
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_SHARE, $this->shareHandle);

        // set up其他 cURL Options
        curl_setopt_array($ch, $options);

        // Execute a request
        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            // Error handling
            echo 'Curl error: ' . curl_error($ch);
        }

        curl_close($ch);

        return $response;
    }
}

2. Add interception logic

In the above code, we have implemented a basic CurlMiddleware class. To make it a middleware, we can control the request and response by adding some interception logic.

We can add pre- and post-operations to intercept and modify requests or responses in the handleRequest method.

 class CurlMiddleware
{
    private $shareHandle;

    public function __construct()
    {
        // Initialize shared resources
        $this->shareHandle = curl_share_init();
    }

    public function __destruct()
    {
        // Destroy shared resources
        if ($this->shareHandle) {
            curl_share_close($this->shareHandle);
        }
    }

    public function beforeRequest($url, $options)
    {
        // Actions performed before sending a request(For example, modify URL 或set up额外的Options)
        $parsedUrl = parse_url($url);
        $url = 'https://m66.net' . $parsedUrl['path'];  // Replace domain name
        return $url;
    }

    public function afterRequest($response)
    {
        // Actions performed after request(For example logging、Response formatting)
        // Here we can make some modifications to the response or record the log
        return $response;
    }

    public function handleRequest($url, $options = [])
    {
        // Pre-operation:Revise URL 或者其他Options
        $url = $this->beforeRequest($url, $options);

        // set up cURL Share resources
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_SHARE, $this->shareHandle);

        // set up其他 cURL Options
        curl_setopt_array($ch, $options);

        // Execute a request
        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            // Error handling
            echo 'Curl error: ' . curl_error($ch);
        }

        curl_close($ch);

        // Post-operation:Processing response
        return $this->afterRequest($response);
    }
}

3. Use middleware

Now, the CurlMiddleware class can execute some intercept logic before and after each request. In actual use, we only need to create a middleware instance and call the handleRequest method to make the request.

 $middleware = new CurlMiddleware();
$options = [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true
];

// ask URL
$url = 'https://example.com/api/data';

// 发送ask
$response = $middleware->handleRequest($url, $options);

// Print response results
echo $response;

4. Shared resource management

Since we use curl_share_init , multiple cURL requests will share the same resources (such as cookies, session information, etc.). This is very useful for situations where state needs to be shared across multiple requests. In our middleware, all cURL requests use the same shared handle, ensuring that they share the same session data.

It should be noted that in some cases, it may be necessary to configure the behavior of curl_share_init , especially when multiple requests require synchronous access to shared resources.

summary

This article shows how to build a middleware interceptor that supports curl_share_init . Through such middleware, we can share session resources and intercept requests and responses when cURL requests are initiated multiple times, so as to perform logging, error processing, URL modification and other operations.