PHP cURL curl_strerror() 函式



PHP cURL 的 curl_strerror() 函式用於返回一個文字錯誤訊息,解釋給定的錯誤程式碼。所以基本上這個函式提供描述性的錯誤訊息,這使得除錯和輕鬆處理錯誤變得容易。

語法

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

string curl_strerror (int $errornum)

引數

此函式接受 $errornum 引數,它是來自 cURL 錯誤程式碼常量之一的錯誤程式碼。

返回值

curl_strerror() 函式返回與給定錯誤號相關的錯誤訊息,或者對於無效的錯誤程式碼返回 NULL。

PHP 版本

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

示例 1

以下是 PHP cURL curl_strerror() 函式的基本示例,用於獲取文字錯誤訊息。

<?php
   // Start a cURL session with a wrong protocol in the URL
   $ch = curl_init("htp://example.com/");
   
   // Execute the cURL session
   curl_exec($ch);
   
   // Check if there is any error and show the error message
   if ($errno = curl_errno($ch)) {
       $error_message = curl_strerror($errno);
       echo "cURL error ({$errno}):\n {$error_message}";
   }
   
   // End the cURL session
   curl_close($ch);
?>

輸出

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

cURL error (1):
 Unsupported protocol

示例 2

在下面的 PHP 程式碼中,我們將使用一個無效的 URL 並檢視 curl_strerror() 函式返回的錯誤訊息。

<?php
   // Start a cURL session
   $ch = curl_init("http://invalid.url");
   
   // Perform the cURL session
   curl_exec($ch);
   
   // Get the error number
   $error_num = curl_errno($ch);
   
   // Get the error message
   $error_message = curl_strerror($error_num);
   
   // Display the error message
   echo "Error: $error_message";
   
   // Close the cURL session
   curl_close($ch);
?> 

輸出

這將生成以下輸出:

Error: Couldn't resolve host name

示例 3

現在在下面的程式碼中,我們將為有效的網站 URL 提供一個不存在的頁面,並檢視 curl_strerror() 函式返回的錯誤訊息。

<?php
   // Start a cURL session
   $ch = curl_init("http://abc123.com/nonexistent-page1");
   
   // Perform the cURL session
   curl_exec($ch);
   
   // Check if any error occurred
   if (curl_errno($ch)) {
       // Get the error number and message
       $error_num = curl_errno($ch);
       $error_message = curl_strerror($error_num);
       
       // Display the error message
       echo "Failed to fetch the page. Error: $error_message";
   } else {
       echo "Page fetched successfully.";
   }
   
   // Close the cURL session
   curl_close($ch);
?> 

輸出

這將建立以下輸出:

404 - Not Found

Page fetched successfully.

示例 4

在下面的示例中,我們使用 curl_strerror() 函式來檢查登入時是否發生任何錯誤。

<?php
   // Start a cURL session
   $ch = curl_init("http://abc123.com");
   
   // Perform the cURL session
   curl_exec($ch);
   
   // Check if any error occurred
   if (curl_errno($ch)) {
       // Get the error number and message
       $error_num = curl_errno($ch);
       $error_message = curl_strerror($error_num);
       
       // Log the error message
       error_log("cURL Error: $error_message");
   } else {
       echo "Request successful.";
   }
   
   // Close the cURL session
   curl_close($ch);
?> 

輸出

以下是上述程式碼的輸出:

Request successful.
php_function_reference.htm
廣告