PHP Conference Japan 2024

CURLFile::__construct

curl_file_create

(PHP 5 >= 5.5.0,PHP 7,PHP 8)

CURLFile::__construct -- curl_file_create建立 CURLFile 物件

說明

物件導向風格

公開 CURLFile::__construct(字串 $filename, 字串|null $mime_type = null, 字串|null $posted_filename = null)

程序式風格

curl_file_create(字串 $filename, 字串|null $mime_type = null, 字串|null $posted_filename = null): CURLFile

建立一個 CURLFile 物件,用於使用 CURLOPT_POSTFIELDS 上傳檔案。

參數

filename

要上傳的檔案路徑。

mime_type

檔案的 MIME 類型。

posted_filename

要在上傳資料中使用的檔案名稱。

返回值

返回一個 CURLFile 物件。

更新日誌

版本 說明
8.0.0 mime_typeposted_filename 現在可以為 null;之前它們的預設值是 0

範例

範例 #1 CURLFile::__construct() 範例

物件導向風格

<?php
/* http://example.com/upload.php:
<?php var_dump($_FILES); ?>
*/

// 建立一個 cURL 句柄
$ch = curl_init('http://example.com/upload.php');

// 建立一個 CURLFile 物件
$cfile = new CURLFile('cats.jpg','image/jpeg','test_name');

// 指派 POST 資料
$data = array('test_file' => $cfile);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

// 執行句柄
curl_exec($ch);
?>

程序式風格

<?php
/* http://example.com/upload.php:
<?php var_dump($_FILES); ?>
*/

// 建立 cURL 句柄
$ch = curl_init('http://example.com/upload.php');

// 建立 CURLFile 物件
$cfile = curl_file_create('cats.jpg','image/jpeg','test_name');

// 指定 POST 資料
$data = array('test_file' => $cfile);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

// 執行句柄
curl_exec($ch);
?>

上述範例將會輸出

array(1) {
  ["test_file"]=>
  array(5) {
    ["name"]=>
    string(9) "test_name"
    ["type"]=>
    string(10) "image/jpeg"
    ["tmp_name"]=>
    string(14) "/tmp/phpPC9Kbx"
    ["error"]=>
    int(0)
    ["size"]=>
    int(46334)
  }
}

範例 #2 CURLFile::__construct() 上傳多個檔案的範例

物件導向風格

<?php
$request
= curl_init('http://www.example.com/upload.php');
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_SAFE_UPLOAD, true);
// 使用 CURLOPT_SAFE_UPLOAD
curl_setopt($request, CURLOPT_POSTFIELDS, [
'blob[0]' => new CURLFile(realpath('first-file.jpg'), 'image/jpeg'), // 使用 CURLFile 上傳檔案
'blob[1]' => new CURLFile(realpath('second-file.txt'), 'text/plain'),
'blob[2]' => new CURLFile(realpath('third-file.exe'), 'application/octet-stream'),
]);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true); // 將結果回傳,而不是直接輸出

echo
curl_exec($request); // 顯示伺服器回傳的結果

var_dump(curl_getinfo($request)); // 顯示 cURL 傳輸資訊

curl_close($request); // 關閉 cURL 資源

程序式風格

<?php
// 程序化
$request = curl_init('http://www.example.com/upload.php');
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_SAFE_UPLOAD, true);
curl_setopt($request, CURLOPT_POSTFIELDS, [
'blob[0]' => curl_file_create(realpath('first-file.jpg'), 'image/jpeg'),
'blob[1]' => curl_file_create(realpath('second-file.txt'), 'text/plain'),
'blob[2]' => curl_file_create(realpath('third-file.exe'), 'application/octet-stream'),
]);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);

echo
curl_exec($request);

var_dump(curl_getinfo($request));

curl_close($request);

上述範例將會輸出

array(26) {
  ["url"]=>
  string(31) "http://www.example.com/upload.php"
  ["content_type"]=>
  string(24) "text/html; charset=UTF-8"
  ["http_code"]=>
  int(200)
  ["header_size"]=>
  int(198)
  ["request_size"]=>
  int(196)
  ["filetime"]=>
  int(-1)
  ["ssl_verify_result"]=>
  int(0)
  ["redirect_count"]=>
  int(0)
  ["total_time"]=>
  float(0.060062)
  ["namelookup_time"]=>
  float(0.028575)
  ["connect_time"]=>
  float(0.029011)
  ["pretransfer_time"]=>
  float(0.029121)
  ["size_upload"]=>
  float(3230730)
  ["size_download"]=>
  float(811)
  ["speed_download"]=>
  float(13516)
  ["speed_upload"]=>
  float(53845500)
  ["download_content_length"]=>
  float(811)
  ["upload_content_length"]=>
  float(3230730)
  ["starttransfer_time"]=>
  float(0.030355)
  ["redirect_time"]=>
  float(0)
  ["redirect_url"]=>
  string(0) ""
  ["primary_ip"]=>
  string(13) "0.0.0.0"
  ["certinfo"]=>
  array(0) {
  }
  ["primary_port"]=>
  int(80)
  ["local_ip"]=>
  string(12) "0.0.0.0"
  ["local_port"]=>
  int(34856)
}

另請參閱

新增註記

使用者貢獻的註記 2 則註記

7
CertaiN
10 年前
multipart POST 請求存在「@」問題。

PHP 5.5 或更高版本的解決方案
- 啟用 CURLOPT_SAFE_UPLOAD。
- 使用 CURLFile 取代「@」。

PHP 5.4 或更早版本的解決方案
- 自行建構 multipart 內容主體。
自行更改「Content-Type」標頭。

以下程式碼片段會對您有所幫助 :D

<?php

/**
* For safe multipart POST request for PHP5.3 ~ PHP 5.4.
*
* @param resource $ch cURL resource
* @param array $assoc "name => value"
* @param array $files "name => path"
* @return bool
*/
function curl_custom_postfields($ch, array $assoc = array(), array $files = array()) {

// invalid characters for "name" and "filename"
static $disallow = array("\0", "\"", "\r", "\n");

// build normal parameters
foreach ($assoc as $k => $v) {
$k = str_replace($disallow, "_", $k);
$body[] = implode("\r\n", array(
"Content-Disposition: form-data; name=\"{$k}\"",
"",
filter_var($v),
));
}

// build file parameters
foreach ($files as $k => $v) {
switch (
true) {
case
false === $v = realpath(filter_var($v)):
case !
is_file($v):
case !
is_readable($v):
continue;
// or return false, throw new InvalidArgumentException
}
$data = file_get_contents($v);
$v = call_user_func("end", explode(DIRECTORY_SEPARATOR, $v));
$k = str_replace($disallow, "_", $k);
$v = str_replace($disallow, "_", $v);
$body[] = implode("\r\n", array(
"Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$v}\"",
"Content-Type: application/octet-stream",
"",
$data,
));
}

// generate safe boundary
do {
$boundary = "---------------------" . md5(mt_rand() . microtime());
} while (
preg_grep("/{$boundary}/", $body));

// add boundary for each parameters
array_walk($body, function (&$part) use ($boundary) {
$part = "--{$boundary}\r\n{$part}";
});

// add final boundary
$body[] = "--{$boundary}--";
$body[] = "";

// set options
return @curl_setopt_array($ch, array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => implode("\r\n", $body),
CURLOPT_HTTPHEADER => array(
"Expect: 100-continue",
"Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type
),
));
}

?>
-5
mipa
10 年前
適用於 PHP < 5.5

<?php

if (!function_exists('curl_file_create')) {
function
curl_file_create($filename, $mimetype = '', $postname = '') {
return
"@$filename;filename="
. ($postname ?: basename($filename))
. (
$mimetype ? ";type=$mimetype" : '');
}
}

?>
To Top