php uses curl to simulate the method of uploading files or pictures from browser forms

  • 2021-11-10 09:06:49
  • OfStack

Preface

Using input box in html in browser, we can upload files and choose form elements < input type="file" > Control, the form form needs to set the enctype= "multipart/form-data" property. For example:


<body>

  <form action="UploadFile.php" method="post" enctype="multipart/form-data">

  <input type="file" name="fileUpload" />

  <input type="submit" value=" Upload a file " />

  </form>

</body>

There are always 1 time when we need to upload files directly in the background instead of uploading them in the front end with a browser. At this time, curl of php provides 1 parameter to upload files directly through the background of php.

php uses curl to simulate uploading files

When curl uploads a file, the most important thing is the application of an "@" symbol. Add the @ symbol curl and it will be treated as a file upload.
Specific code examples:


<?php
  header('Content-type:text/html; charset=utf-8'); // Declare encoding 
  $ch = curl_init();
  $url = 'https://xxx.com/api/mobile/auto_upload.php?uid=9705459';
  
  //post Data, use @ Symbols, curl It will be considered that there is a file upload 
  $curlPost = array('Filedata'=>'@/Users/finup/Documents/11.png');
  
  
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_POST, 1); //POST Submit 
  curl_setopt($ch, CURLOPT_POSTFIELDS,$curlPost);
  $data =curl_exec($ch);
  curl_close($ch);
  echo '<pre>';
  var_dump($data);

The url in the above code example is a specific interface for processing file uploading. You can directly use $_ FILES to obtain the relevant information of uploaded temporary files, and print out $_ FILES as follows, in which the key "Filedata" name of the array can be specified by yourself when passing parameters:


Array
(
[Filedata] => Array
(
[name] => 11.png
[type] => application/octet-stream
[tmp_name] => /private/var/tmp/php936cex
[error] => 0
[size] => 36663
)
)

Related articles: