简体   繁体   中英

Php Curl send File with data

I need to upload 3 files along with variables in post data. This is what my call looks like -

$data['type1'] = new CurlFile($file1);
$data['type2'] = new CurlFile($file2);
$data['type3'] = new CurlFile($file3);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data, "var1: $val1", "var2: $val2"); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data', "headkey: $headkeyValue"));

I am not able to get $app->request()->post('var1'); from slim framework. It is empty.

  • I am able to get the headkey from the Header as $app->request()->headers('headkey');
  • I am able to get the data in $_FILES

It's due to the fact that all files uploaded with HTTP POST method are in $_FILES global variable. That's why you cannot access files by this way

$app->request()->post('val1');

but you can by using $_FILES

$_FILES description

An associative array of items uploaded to the current script via the HTTP POST method. The structure of this array is outlined in the POST method uploads section.

Here the sample curl request

$curlFile = curl_file_create($uploaded_file_name_with_full_path);
$post = array('val1' => 'value','val2' => 'value','file_contents'=> $curlFile );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$your_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

Don't forget to put the appropriate header.
You can also find good source here Curl File Upload to send file via CURL. Make sure that you are passing your file on file_contents key in above code.

This is what I did in alignment to 's answer:

$data['type1'] = new CurlFile($file1);
$data['type2'] = new CurlFile($file2);
$data['type3'] = new CurlFile($file3);

//New Code Added
$data['var1'] = "$val1";
$data['var2'] = "$val2";

//removed the trailing string
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM