微信上传临时素材(图片)
/上传临时图片 $img为通过post表单提交过来的图片资源/
function uploadTmpImg($img)
{
$access_token = cacheToken();
$url="https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$access_token}&type=image";
$cfile = curl_file_create($img['tmp_name'],$img['type'],$img['name']);
$data= array("media"=>$cfile);
$url = new Mycurl($url);
$result = $url->http_url($data);
$res = json_decode($result, true);
var_dump($res);
}
$img = $_FILES['img'];
uploadTmpImg($img);
/curl类/
class Mycurl
{
private $url;
function __construct($url)
{
$this->url = $url;
}
//模拟发送get请求
function get()
{
//初始一个curl
$curl = curl_init();
//配置curl的参数
curl_setopt($curl, CURLOPT_URL, $this->url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
//执行一个curl
$content = curl_exec($curl);
//关闭会话
curl_close($curl);
//将该url地址请求的结果返回给你
return $content;
}
//模拟发送post请求
function post($data)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $this->url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
//是否是post请求
curl_setopt($curl, CURLOPT_POST, true);
//post请求所带的数据是什么
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$content = curl_exec($curl);
curl_close($curl);
return $content;
}
//差不多结合get post
function http_url($data = null){
//$data = http_build_query($data);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $this->url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
}