LoginSignup
1
0

PHP、CURLFileでファイルをアップロードする。(multipart/form-data、POST)

Last updated at Posted at 2023-07-18

PHP、CURLFileでファイルをアップロードするコードです。
試行錯誤したので備忘録として残します。
※$_FILES、"Content-Type: multipart/form-data"、POSTを使用しています。

本記事の環境

ホストOS:Windows10 Pro 64bit 8GB
ゲストOS:Red Hat Enterprise Linux release 8.3 (Ootpa)
Oracle VM VirtualBox:6.0.4a
vagrant:Vagrant 2.2.14
Apache:2.4.37
PHP:PHP 7.4.15
Tera Term:4.105
コマンドプロンプト
ホストOS側に実ソース

ソースコード

$curl_file = new \CURLFile($_FILES['uploadfile']["tmp_name"], $_FILES['uploadfile']["type"], $_FILES['uploadfile']["name"]);
$option = [
    'aaa' => 'AAA',
    'bbb' => 'BBB',
];
$option_encode = json_encode($option);
$param = [
    // $curl_fileと、その他に必要なパラメータがあればここに追加。
    'file' => $curl_file,
    'pass' => "abcdef",
    'option' => $option_encode,
];
$postdata = $param;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://xxx.jp/yyy/zzz.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: multipart/form-data"));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = curl_exec($ch);
$result_decode = json_decode($result, true);
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0