curl 文件上传
sanlanlan 2020-7-18 标签: PHP 浏览:639 评论:0
curl 文件上传
1.demo 上传文件 (PHP 5.5.0 后被废弃)
/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/
$ch = curl_init();
$data = array('name' => 'Foo', 'file' => '@/home/user/test.png');
curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); // PHP 5.6.0 后必须开启
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
传递一个数组到CURLOPT_POSTFIELDS,cURL会把数据编码成 multipart/form-data,而然传递一个URL-encoded字符串时,数据会被编码成 application/x-www-form-urlencoded。
2.php 5.5 后使用 CURLFile 实现上传
CURLFile 应该与选项 CURLOPT_POSTFIELDS 一同使用用于上传文件。
function makeCurlFile($file){
$mime = mime_content_type($file);
$info = pathinfo($file);
$name = $info['basename'];
$output = new CURLFile($file, $mime, $name);
return $output;
}
Then construct an array of all the form fields you want to post. For each file upload just add the CURLFiles.
$ch = curl_init("https://api.example.com");
$mp3 =makeCurlFile($audio);
$photo = makeCurlFile($picture);
$data = array(
'mp3' => $mp3,
'picture' => $photo,
'name' => 'My latest single',
'description' => 'Check out my newest song'
);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
if (curl_errno($ch)) {
$result = curl_error($ch);
}
curl_close ($ch);
1.demo 上传文件 (PHP 5.5.0 后被废弃)
/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/
$ch = curl_init();
$data = array('name' => 'Foo', 'file' => '@/home/user/test.png');
curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); // PHP 5.6.0 后必须开启
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
传递一个数组到CURLOPT_POSTFIELDS,cURL会把数据编码成 multipart/form-data,而然传递一个URL-encoded字符串时,数据会被编码成 application/x-www-form-urlencoded。
2.php 5.5 后使用 CURLFile 实现上传
CURLFile 应该与选项 CURLOPT_POSTFIELDS 一同使用用于上传文件。
function makeCurlFile($file){
$mime = mime_content_type($file);
$info = pathinfo($file);
$name = $info['basename'];
$output = new CURLFile($file, $mime, $name);
return $output;
}
Then construct an array of all the form fields you want to post. For each file upload just add the CURLFiles.
$ch = curl_init("https://api.example.com");
$mp3 =makeCurlFile($audio);
$photo = makeCurlFile($picture);
$data = array(
'mp3' => $mp3,
'picture' => $photo,
'name' => 'My latest single',
'description' => 'Check out my newest song'
);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
if (curl_errno($ch)) {
$result = curl_error($ch);
}
curl_close ($ch);
发表评论: