PHP cURL curl_share_setopt() 函式



PHP cURL 的 curl_share_setopt() 函式用於設定 cURL 共享控制代碼的選項。此函式允許您在多個 cURL 控制代碼之間共享資料,例如 Cookie 和 DNS 快取。

語法

以下是 PHP cURL curl_share_setopt() 函式的語法:

bool curl_share_setopt (resource $sh, int $option, mixed $value)

引數

以下是 curl_share_setopt() 函式的引數:

  • $sh - 它是由 curl_share_init() 返回的 cURL 共享控制代碼。

  • $option - 要設定的選項,例如 CURLSHOPT_SHARE、CURLSHOPT_UNSHARE。

  • $value - 選項的值。它可以是 CURL_LOCK_DATA_COOKIE、CURL_LOCK_DATA_DNS 或 CURL_LOCK_DATA_SSL_SESSION。

返回值

curl_share_setopt() 函式在成功時返回 TRUE,失敗時返回 FALSE。

PHP 版本

curl_share_setopt() 函式首次引入核心 PHP 5.5.0,並在 PHP 7 和 PHP 8 中繼續輕鬆執行。

示例 1

首先,我們將向您展示 PHP cURL curl_share_setopt() 函式設定共享 Cookie 選項的基本示例。

<?php
   // Create a cURL share handle
   $sh = curl_share_init();
   
   // Set an option 
   curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);
   
   // Create a cURL handle
   $ch = curl_init('http://example.com');
   
   // Set the cURL handle 
   curl_setopt($ch, CURLOPT_SHARE, $sh);
   
   // Execute the cURL session
   curl_exec($ch);
   
   // Close the cURL handle
   curl_close($ch);
   
   // Close the share handle
   curl_share_close($sh);
?>

輸出

此處將顯示 URL 的內容:

curl_share_setopt Output

示例 2

在下面的 PHP 程式碼中,我們將使用 curl_share_setopt() 函式設定共享 DNS 快取的選項,例如 CURLSHOPT_SHARE 和 CURL_LOCK_DATA_DNS。

<?php
   // Create a cURL share handle
   $sh = curl_share_init();
   
   // Set an option 
   curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);
   
   // Create a cURL handle
   $ch1 = curl_init('http://example1.com');
   $ch2 = curl_init('http://example2.com');
   
   // Set the cURL handles 
   curl_setopt($ch1, CURLOPT_SHARE, $sh);
   curl_setopt($ch2, CURLOPT_SHARE, $sh);
   
   // Execute the cURL sessions
   curl_exec($ch1);
   curl_exec($ch2);
   
   // Close the cURL handles
   curl_close($ch1);
   curl_close($ch2);
   
   // Close the share handle
   curl_share_close($sh);   
?> 

輸出

此處將顯示 URL 內容:

curl_share_setopt Output

示例 3

現在,以下程式碼使用 curl_share_setopt() 函式設定共享 SSL 會話的選項,使用 CURLSHOPT_SHARE 和 CURL_LOCK_DATA_SSL_SESSION。

<?php
   // Create a cURL share handle
   $sh = curl_share_init();
   
   // Set an option to share SSL sessions
   curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION);
   
   // Create a cURL handle
   $ch = curl_init('https://acb123.com');
   
   // Set the cURL handle to use the share handle
   curl_setopt($ch, CURLOPT_SHARE, $sh);
   
   // Execute the cURL session
   curl_exec($ch);
   
   // Unshare SSL sessions
   curl_share_setopt($sh, CURLSHOPT_UNSHARE, CURL_LOCK_DATA_SSL_SESSION);
   
   // Close the cURL handle
   curl_close($ch);
   
   // Close the share handle
   curl_share_close($sh);
   
?> 

輸出

這將建立以下輸出:

curl_share_setopt Output
php_function_reference.htm
廣告