php curl发送数据和文件

function mycurl($file, $url, $aid) {
// 如果文件名是中文名,将中文字符编码转换一下
$file=iconv("UTF-8","gb2312", $file);
$data = [
// 还有一种打成数据流的方法.
'pic'=>new CURLFile($file),
'name' => 'qb',
// 自定义盐签
'token' => 'e10adc3949ba59abbe56e057f20f883e',
'aid' => $aid
];
// 创建一个新cURL资源
$ch = curl_init();

// 设置URL和相应的选项
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 跳过证书验证(https)的网站无法跳过,会报错
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书验证
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回的数据不打印

//伪造网页来源地址,伪造来自百度的表单提交
curl_setopt($ch, CURLOPT_REFERER, "http://www.baidu.com");
curl_setopt($ch, CURLOPT_POST, 1); //表单数据,是正规的表单设置值为非0

/**
* 使用数组提供post数据时,CURL组件大概是为了兼容@filename这种上传文件的写法,
* 默认把content_type设为了multipart/form-data。虽然对于大多数web服务器并
没有影响,但是还是有少部分服务器不兼容。本文得出的结论是,在没有需要上传文件的
情况下,尽量对post提交的数据进行http_build_query,然后发送出去,能实现更好的兼容性,更小的请求数据包。
* curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
*/
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 100); //设置curl执行超时时间最大是多少
// 抓取URL并把它传递给浏览器
$rs = curl_exec($ch);
if($rs === false) {
return 'Curl error: ' . curl_error($ch);
}
// 关闭cURL资源,并且释放系统资源
curl_close($ch);
return $rs;
}

上面是发送文件

下面是接受文件


/**
* 获取file数据
* @return array
*/
public function get_file()
{
// file 文件
$file = $_FILES;
// 其他参数
$post = $_POST;
// 接口盐签
$tokne = 'e10adc3949ba59abbe56e057f20f883e';

if (empty($file) || empty($post)) {
$res = ['code' => 199, 'msg' => '文件丢失!'];
echo json_encode($res);
     exit;
}

if ($post['token'] != $tokne) {
$res = ['code' => 199, 'msg' => '鉴权失败!'];
     echo json_encode($res);
     exit;
    }

if ($file) {
$file_data = $this->file_move($file, $post['aid']);
if (!empty($file_data)) {
$res = ['code' => 200, 'msg' => '头像上传成功!'];
        echo json_encode($res);
        exit;
        } else {
$res = ['code' => 199, 'msg' => '头像存储失败!'];
        echo json_encode($res);
        exit;
        }
}
}


/*
* * 接口获取file类型文件直接转存 * @param $file * @param $aid -- 用户aid * @return array|string */ public function file_move($file, $aid) { $data = ''; foreach ($file as $image) { $name = $image['name']; $type = strtolower(substr($name, strrpos($name, '.') + 1)); $allow_type = ['jpg', 'jpeg', 'gif', 'png']; //判断文件类型是否被允许上传 if (!in_array($type, $allow_type)) { continue; } // 文件名 // $file_name = date('Ymd') . time() . rand(100, 999) . '.' . $type; // app_id 命名 $file_name = $aid . '.' . $type; //开始移动文件到相应的文件夹 if (move_uploaded_file($image['tmp_name'], ROOT_PATH . 'public' . DS . 'data' . DS . 'image' . DS . $file_name)) { $data = ROOT_PATH . 'public' . DS . 'data' . DS . 'image' . DS . $file_name; } } return $data; }
原文地址:https://www.cnblogs.com/init-007/p/12750910.html