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

Drupal 中使用 cURL 實現文件 POST 上傳

     編輯:PHP 相關知識

背景與需求

Drupal 雖提供 drupal_http_request 執行 HTTP 請求,但在文件上傳場景下,cURL 靈活度更高。本文演示如何在 Drupal 模組中使用 cURL 模擬 multipart/form-data 表單提交,上傳文件至遠程服務器。

目標表單結構

<form enctype="multipart/form-data" method="POST" action="https://example.com/upload.php">
  <input name="username" type="text" />
  <input name="password" type="password" />
  <input type="checkbox" name="rememberme" />
  <input name="avatar" type="file" />
</form>

Drupal cURL 實現代碼

<?php
$url = 'https://example.com/upload.php';
$ch = curl_init();

curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);

$post = array(
    'username' => 'user123',
    'password' => 'pass456',
    'rememberme' => '1',
    'avatar' => '@' . $file_path,  // @ 前綴表示文件上傳
);

curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);

if (curl_errno($ch)) {
    watchdog('mymodule', 'cURL error: @error', array('@error' => curl_error($ch)), WATCHDOG_ERROR);
}

curl_close($ch);
// $response 包含遠程服務器返回的 HTML 響應
?>

關鍵要點解析

  • @ 前綴:cURL 5.5+ 版本中,CURLOPT_POSTFIELDS 數組值以 @ 開頭表示文件上傳,需提供絕對路徑
  • CURLOPT_RETURNTRANSFER:設置為 true 將響應作為字符串返回而非直接輸出
  • 錯誤處理:生產環境必須檢查 curl_errno() 並記錄日誌
  • 安全性:上傳前驗證文件類型、大小,防止惡意文件上傳

Drupal 7 完整模組示例

function mymodule_upload_file($file_path, $remote_url) {
  if (!file_exists($file_path)) {
    return array('success' => FALSE, 'error' => 'File not found');
  }
  
  $ch = curl_init($remote_url);
  curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_POSTFIELDS => array(
      'file' => '@' . realpath($file_path),
      'fid' => '123',
    ),
    CURLOPT_SSL_VERIFYPEER => FALSE, // 僅測試環境使用
  ));
  
  $response = curl_exec($ch);
  $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);
  
  return array(
    'success' => ($http_code == 200),
    'response' => $response,
    'http_code' => $http_code,
  );
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved