PHP cURL curl_close() 函式



PHP 客戶端 URL curl_close() 函式用於關閉 cURL 會話並釋放與其相關的所有資源。要使用此函式,您需要使用 curl_init() 初始化 cURL 會話。

此函式沒有產生任何效果。在 PHP 8.0.0 版本之前,此函式用於關閉資源。

語法

以下是 PHP cURL curl_close() 函式的語法 -

void curl_close ( resource $ch )

引數

此函式接受 $ch 引數,它是 curl_init() 返回的 cURL 處理資源。

返回值

curl_close() 函式不返回值,因為它只是關閉會話。

PHP 版本

curl_close() 函式在核心 PHP 4.0.2 中引入,可以很好地與 PHP 5、PHP 7 和 PHP 8 協同工作。

示例 1

首先,我們將向您展示 PHP cURL curl_close() 函式關閉 cURL 會話並釋放資源的基本示例。

<?php
   // create a new cURL resource
   $ch = curl_init();

   // Set URL and other appropriate options
   curl_setopt($ch, CURLOPT_URL, "https://tutorialspoint.tw/");
   curl_setopt($ch, CURLOPT_HEADER, 0);

   // Grab URL and pass it to the browser
   curl_exec($ch);

   // Close cURL resource
   curl_close($ch);

   echo "The session is closed successfully.";

輸出

以下是以下程式碼的結果 -

The session is closed successfully.

示例 2

這是一個額外的 PHP 示例程式碼,它使用 curl_close() 方法透過處理錯誤來結束會話。

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

   // Set the URL to fetch
   curl_setopt($ch, CURLOPT_URL, "https://tutorialspoint.tw");

   // Return the transfer as a string instead of outputting it directly
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

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

   // Check if any error occurred
   if(curl_errno($ch)) {
      echo 'cURL Error: ' . curl_error($ch);
   } else {
      // Print the output
      echo $output;
   }

   // Close the cURL session to free up resources
   curl_close($ch);

   echo "The session is closed successfully.";
?> 

輸出

這將產生以下輸出 -

The session is closed successfully.

示例 3

這是一個額外的示例,用於檢視透過從 API 端點獲取 JSON 資料並進行處理來使用 curl_close() 函式的方式。處理完資料後,使用 curl_close() 函式關閉會話。

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

   // Set the URL to fetch JSON data
   $url = "https://jsonplaceholder.typicode.com/posts/1";
   curl_setopt($ch, CURLOPT_URL, $url);

   // Return the transfer as a string instead of outputting it directly
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

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

   // Check for errors
   if (curl_errno($ch)) {
      echo 'cURL Error: ' . curl_error($ch);
   } else {
      // Decode JSON response
      $data = json_decode($response, true);

      // Process the data
      if ($data) {
         echo "Title: " . $data['title'] . "<br>";
         echo "Body: " . $data['body'];
      } else {
         echo "Error decoding JSON data.";
      }
   }

   // Close cURL resource
   curl_close($ch);
?> 

輸出

這將生成以下輸出 -

Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
Body: quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto

總結

curl_close() 方法是一個內建函式,用於關閉已開啟的會話以節省資源。您可以透過呼叫此函式來終止 cURL 會話並阻止指令碼使用系統資源。

php_function_reference.htm
廣告