本篇文章給大家帶來的內容是關於php擷取臨時素材的方法(附代碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所協助。
注意:1:媒體檔案在後台儲存時間為3天,即3天后media_id失效。
2:臨時素材media_id是可複用的。
如果是php5.3以下的版本path路徑需要帶上@,加文本絕對路徑,5.3以上的版本需要用new curlFile()類擷取絕對位址
$path = new CURLFile(realpath('G:/xampp/htdocs/wx/app/zan.jpg'));$path = $path->name;//絕對路徑$type = 'images';//thumb$res = $this->upload_media('image',$path);//擷取到素材的media_id,有效期間3天$media_id = $res->media_id;//以下是擷取臨時素材url$url = $this->get_media($media_id);//擷取到臨時素材的url public function upload_media($type,$path) { $url = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $this->get_access_token() . '&type=' . $type; $res = $this->upload($url, array('media' => '@'.$path)); // 判斷是否調用成功 return $res; } public function get_media($media_id) { return 'https://api.weixin.qq.com/cgi-bin/media/get?access_token=' . $this->get_access_token() . '&media_id=' . $media_id; } /* * 上傳圖片。圖文專用 */ public static function upload($url, $filedata) { $curl = curl_init (); if (class_exists ( '/CURLFile' )) {//php5.5跟php5.6中的CURLOPT_SAFE_UPLOAD的預設值不同 curl_setopt ( $curl, CURLOPT_SAFE_UPLOAD, true ); } else { if (defined ( 'CURLOPT_SAFE_UPLOAD' )) { curl_setopt ( $curl, CURLOPT_SAFE_UPLOAD, false ); } } curl_setopt ( $curl, CURLOPT_URL, $url ); curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, FALSE ); curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, FALSE ); if (! empty ( $filedata )) { curl_setopt ( $curl, CURLOPT_POST, 1 ); curl_setopt ( $curl, CURLOPT_POSTFIELDS, $filedata ); } curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 ); $output = curl_exec ( $curl ); curl_close ( $curl ); return $output; }