Update: scroll for my solution.
This site has API access to upload files directly to its servers and I success to perform all API calls using cURL post/get but unfortunately, in the upload stage he provided only HTML form.
<form enctype="multipart/form-data" action="https://s1.youdbox.com/upload/01" method="post">
<input name="sess_id" value="3qr5wkukoy31pd1g">
<input name="file" type="file">
</form>
I tried many times to figure out how to perform upload using cURL post but it always failed But when I create a HTML file and use the above upload form then add the upload data manually it success and works fine
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch1, CURLOPT_URL, $server_url);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch1, CURLOPT_POST, 1);
$upload_data = array(
'sess_id' => $sesson_id,
#'file' => '@' .realpath('test.txt')
'file' => $file
);
$headers = array();
$headers[] = 'multipart/form-data';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch1, CURLOPT_POSTFIELDS, $upload_data);
$up_result = curl_exec($ch1);
if (curl_errno($ch1)) {
echo 'Error:' . curl_error($ch1);
}
curl_close($ch1);
var_dump($up_result);
For people who are searching for a solution about this issue/question, here is my solution that I reached after debug and test.
Hint: Don't use '@' symbol while define the file path because cURL will handle it.
$file = '/path-to-your-file/test.txt';
$mime = mime_content_type($file);
$name = basename($file);
$url = 'https//example.com/api/url';
$data = curl_file_create($file, $mime, $name);
#$data = new CURLFile($file, $mime, $name); // uncomment if create method didn't work
$ch = curl_init();
// Don't do SSL verify or check (un-comment if you want it)
#curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
#curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$post_field = array(
'key1' => 'value1',
'key2' => 'value2',
'file' => $data
);
$headers = array();
$headers[] = 'multipart/form-data';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_field);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
$result = json_decode($response, true);
print_r($result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.