Skip to content

Instantly share code, notes, and snippets.

@imty42
Last active November 30, 2015 04:30
Show Gist options
  • Save imty42/b5336972152120791417 to your computer and use it in GitHub Desktop.
Save imty42/b5336972152120791417 to your computer and use it in GitHub Desktop.
php cUrl multipart form-data upload
$tmp_name = "";
$tmp_size = 0;
foreach ($_FILES as $v) {
  $tmp_name = $v["tmp_name"];
  $tmp_size = $v["size"];
}

$destination = "your_post_api_here";

if (class_exists('\CURLFile')) {
  // version_compare(phpversion(), '5.4.0') >= 0
  $post = array('fieldname' => new \CURLFile(realpath($tmp_name)));
} else {
  $post = array('fieldname' => '@' . realpath($tmp_name));
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$destination);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: multipart/form-data"));
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_INFILESIZE, $tmp_size);
$result = json_decode(curl_exec ($ch), true);
curl_close ($ch);

// var_dump($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment