简体   繁体   中英

Multipart/form-data using PHP

I have written an multipart/form-data html which a user can upload directly to AWS S3. However, I'm looking to use a PHP fwrite() to create the file to be uploaded. I generate a csv using PHP when the page loads, and then I want that file to be automatically used for the multipart/form-data upload. Here is that code:

 <form action="https://s3.amazonaws.com/my.data" method="post" enctype="multipart/form-data">
  <input type="hidden" name="key" value="uploads/${filename}">
  <input type="hidden" name="AWSAccessKeyId" value="xxxxxxxx"> 
  <input type="hidden" name="acl" value="private"> 
  <input type="hidden" name="success_action_redirect" value="http://thanks.html">
  <input type="hidden" name="policy" value="xxxxxxxxxx">
  <input type="hidden" name="signature" value="xxxxxxxxx">
  <input type="hidden" name="Content-Type" value="">
  <!-- Include any additional input fields here -->

  File to upload to S3: 
  <input name="file" type="file"> 
  <br> 
  <input type="submit" value="Upload File to S3"> 
</form> 

 <?php
 $email = "testemail@gmail.com";
 $art_fair = 0;

//this is where the creating of the csv takes place
$cvsData = $email . "," . $art_fair . "\n";

$fp = fopen("formTest.csv","a"); // $fp is now the file pointer to new file to create

if($fp){
fwrite($fp,$cvsData); // Write information to the file
fclose($fp); // Close the file
}
?>

I'm trying to figure out how to combine these together to make it work. Thanks!

What is point of rendering a form when you dont actually want any file to be selected??? Using this approach has a lot of flaws.Most importantly, you are inviting people to play around with your credentials.Further, there isn't any input that you are taking from the client.So why not generate the csv file directly and upload it through a POST request via cURL!!! You also get a speed boost by using curl.

Heres how you can do it:

//Make an array of your POST Parameters
$params=array(
   "file"=>realpath('formTest.csv'),  //This will generate the path to csv file you want to send 
  "AWSAccessKeyId"=>'xxxxxx',
  ......
  ......
 );

// initialise the curl request
$request = curl_init('https://s3.amazonaws.com/my.data');

// send a file
curl_setopt($request, CURLOPT_POST, true);
curl_setopt(
    $request,
    CURLOPT_POSTFIELDS,http_build_query($params)
  );

//Set The Header to Multipart
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));

// output the response
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($request);

// close connection
curl_close($request);

Add this code after you have written the csv file.

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