/** * 上传临时素材,有效期为3天(认证后的订阅号可用) * 注意:上传大文件时可能需要先调用 set_time_limit(0) 避免超时 * 注意:数组的键值任意,但文件名前必须加@,使用单引号以避免本地路径斜杠被转义 * 注意:临时素材的media_id是可复用的! * @param array $data {"media":'@Path\filename.jpg'} * @param type 类型:图片:image 语音:voice 视频:video 缩略图:thumb * @return boolean|array */ public function uploadMedia($data,$access_token){ //原先的上传多媒体文件接口使用 self::UPLOAD_MEDIA_URL 前缀 $result = $this->http_post('https://api.weixin.qq.com/cgi-bin/media/upload?access_token='.$access_token.'&type=image',$data,true); if ($result) { $json = json_decode($result,true); if (!$json || !empty($json['errcode'])) { $this->errCode = $json['errcode']; $this->errMsg = $json['errmsg']; return false; } return $json; } return false; } /** * POST 请求 * @param string $url * @param array $param * @param boolean $post_file 是否文件上传 * @return string content */ private function http_post($url,$param,$post_file=false){ $oCurl = curl_init(); if(stripos($url,"https://")!==FALSE){ curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1 } if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) { $is_curlFile = true; } else { $is_curlFile = false; if (defined('CURLOPT_SAFE_UPLOAD')) { curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false); } } if (is_string($param)) { $strPOST = $param; }elseif($post_file) { if($is_curlFile) { foreach ($param as $key => $val) { if (substr($val, 0, 1) == '@') { $param[$key] = new \CURLFile(realpath(substr($val,1))); } } } $strPOST = $param; } else { $aPOST = array(); foreach($param as $key=>$val){ $aPOST[] = $key."=".urlencode($val); } $strPOST = join("&", $aPOST); } curl_setopt($oCurl, CURLOPT_URL, $url); curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt($oCurl, CURLOPT_POST,true); curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST); $sContent = curl_exec($oCurl); $aStatus = curl_getinfo($oCurl); curl_close($oCurl); if(intval($aStatus["http_code"])==200){ return $sContent; }else{ return false; } }
---------------------或者----------
$filepath = 'Public/learn/1560844764139.jpg'; /* 使用exec函数 */ $command = 'curl -F media=@'.$filepath.' "https://api.weixin.qq.com/cgi-bin/media/upload?access_token='.$token.'&type=image"'; $retval = array(); exec($command, $retval, $status); $params = json_decode($retval[0],true);
----------或------------
/* 使用system函数 */
$command = 'curl -F media=@'.$filepath.' "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=image"';
$retval = 1;
$last_line = system($command, $retval);
$params = array();
$params = json_decode($last_line,true);
if ($retval != 0) {
if (isset($params['errcode'])) {
$params = array(
'errcode' => '-100',
'errmsg' => '公众号服务出错,请联系管理员',
);
}
}
return $params;