The content of this article is about how PHP uses curl to simulate browser forms to upload files and pictures. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Preface
We can upload files using the input box in HTML in the browser. The form element selects the control. The form form needs to set enctype= "multipart/form-data" attribute. For example:
<body> <form action="UploadFile.php" method="post" enctype="multipart/form-data"> <input type="file" name="fileUpload" /> <input type="submit" value="上传文件" /> </form> </body>
There are always times when we need to upload files directly in the background instead of using the browser to upload files on the front end. At this time, PHP's curl provides some parameters to upload files directly through the PHP background.
php uses curl to simulate uploading files
When curl uploads files, the most important thing is the application of the "@" symbol. Adding the @ symbol will curl it Treat it as a file upload.
Specific code example:
<?php header('Content-type:text/html; charset=utf-8'); //声明编码 $ch = curl_init(); $url = 'https://xxx.com/api/mobile/auto_upload.php?uid=9705459'; //post数据,使用@符号,curl就会认为是有文件上传 $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提交 curl_setopt($ch, CURLOPT_POSTFIELDS,$curlPost); $data =curl_exec($ch); curl_close($ch); echo '<pre class="brush:php;toolbar:false">'; var_dump($data);
The URL in the above code example is a specific interface for processing file uploads. You can directly use $_FILES to obtain information about uploaded temporary files and print out $_FILES As follows, the array key "Filedata" name 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 ) )
The above is the detailed content of PHP uses curl to simulate the method of uploading files and images through browser forms. For more information, please follow other related articles on the PHP Chinese website!