PHP Persistent cURL Share Handles

PHP 8.5 adds persistent cURL share handles. They allow selected cURL caches, such as DNS and connection information, to survive across PHP requests instead of being recreated every time.

Create a Persistent Share Handle

Example:

<?php

$share = curl_share_init_persistent([
    CURL_LOCK_DATA_DNS,
    CURL_LOCK_DATA_CONNECT,
]);

If PHP finds an existing persistent handle with the same share options, it can reuse it.

Attach It to a cURL Request

Example:

<?php

$share = curl_share_init_persistent([
    CURL_LOCK_DATA_DNS,
    CURL_LOCK_DATA_CONNECT,
]);

// Replace this URL with the HTTPS service you call.
$curl = curl_init('https://example.com/');

curl_setopt($curl, CURLOPT_SHARE, $share);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);

try {
    $response = curl_exec($curl);
    if ($response === false) {
        throw new RuntimeException(curl_error($curl));
    }
    echo "HTTP " . curl_getinfo($curl, CURLINFO_HTTP_CODE);
} finally {
    unset($curl);
}

Releasing the last reference to the ordinary cURL handle frees that handle. The persistent share handle can remain available to later requests in the same worker process. curl_close() has no effect in PHP 8 and is deprecated in PHP 8.5. HTTP 4xx/5xx responses still need application-level handling; they are not always transport failures.

What Can Be Shared?

The function accepts a non-empty array of supported CURL_LOCK_DATA_* values.

Shared data Benefit
DNS cache Avoid repeated name resolution
Connection cache Increase the chance of connection reuse

Cookies Are Not Allowed

CURL_LOCK_DATA_COOKIE is not allowed for persistent share handles. Persisting cookies across unrelated web requests could mix sensitive session data between users.

Persistent connection state should only be shared when requests target services where that reuse is appropriate.

Persistent vs Normal Share Handles

Example:

<?php

$normal = curl_share_init();

$persistent = curl_share_init_persistent([
    CURL_LOCK_DATA_DNS,
]);

A normal share handle belongs to the current PHP request. A persistent share handle can be reused by later requests handled by the same PHP environment.

When It Helps

This feature is useful for applications that repeatedly call the same external APIs. Reusing DNS and connection caches can reduce repeated setup work, especially when many short PHP requests talk to the same hosts.

Conclusion

curl_share_init_persistent() gives PHP 8.5 a way to reuse selected cURL caches across requests. Share only the cache types you need and avoid treating persistent state as user-specific storage.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram