首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 程式與伺服器端通訊的方法

     編輯:PHP 相關知識

注意

原文內容似為 Excel FV 函數(未來值)財務計算教學,與標題「PHP 程式與伺服器端通訊」不符。此處依標題重寫相關主題。

PHP 與伺服器端通訊常見方式

1. cURL 库(最推薦)

$ch = curl_init('https://api.example.com/endpoint');
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => http_build_query(['key' => 'value']),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/x-www-form-urlencoded'],
    CURLOPT_TIMEOUT        => 10,
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
    throw new Exception(curl_error($ch));
}
curl_close($ch);
$data = json_decode($response, true);

2. Stream Context(原生,無需擴展)

$opts = [
    'http' => [
        'method'  => 'POST',
        'header'  => 'Content-Type: application/x-www-form-urlencoded',
        'content' => http_build_query(['key' => 'value']),
        'timeout' => 10,
    ]
];
$context = stream_context_create($opts);
$response = file_get_contents('https://api.example.com/endpoint', false, $context);
$data = json_decode($response, true);

3. fsockopen(底層 Socket,需手組 HTTP 協定)

$fp = fsockopen('ssl://api.example.com', 443, $errno, $errstr, 10);
if ($fp) {
    $req = "POST /endpoint HTTP/1.1\r\n";
    $req .= "Host: api.example.com\r\n";
    $req .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $req .= "Content-Length: " . strlen($body) . "\r\n";
    $req .= "Connection: close\r\n\r\n";
    $req .= $body;
    fwrite($fp, $req);
    $resp = '';
    while (!feof($fp)) $resp .= fgets($fp, 1024);
    fclose($fp);
    // 需自行解析 HTTP 回應標頭與主體
}

4. SOAP / XML-RPC

使用 SoapClient 或 xmlrpc_encode_request 進行結構化 RPC 呼叫。

最佳實務

  • 優先使用 cURL,功能最完整、效能最好。
  • 統一錯誤處理、重試機制、超時設定。
  • 敏感資訊(API Key)勿硬編碼,使用環境變數或設定檔。
  • 驗證 SSL 憑證(CURLOPT_SSL_VERIFYPEER => true)。
  • 記錄請求/回應日誌便於除錯。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved