普通的CURL上传磁盘文件的方式
发送方 send.php
的代码如下:
<?php
$target_url = "http://localhost/upload.php";
$filename = realpath("test.txt");
/*
* 第一种写法,但是在5.5以上版本不推荐使用
* @$filename 是文件路径,必须有
* filename=test.txt 是接收方收到的文件名,为空时 则取 filename 文件路径中的 basename部分
* type=text/plain 文档类型,可以为空
*/
/*
$post_data = array(
'extra_info' => '123456',
'file_contents' => "@$filename;filename=test.txt;type=text/plain",
);
*/
/*
* 第二种写法,推荐新版本php中使用
* CURLFile参数解释
* @$filename 需要上传的文件,建议使用绝对路径
* @$mimetype: 默认是 application/octet-stream,此处留空
* @$postname: 接收方$_FILES数组中的文件名,此处为 test.txt
*/
$file = new CURLFile($filename, '', 'test.txt');
$post_data = array(
'extra_info' => '123456',
'file_contents' => $file,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
处理上传文件的代码upload.php
示例:
<?php