当前位置:Gxlcms > PHP教程 > php微信获取临时素材的方法(附代码)

php微信获取临时素材的方法(附代码)

时间:2021-07-01 10:21:17 帮助过:188人阅读

本篇文章给大家带来的内容是关于php微信获取临时素材的方法(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

注意:1:媒体文件在微信后台保存时间为3天,即3天后media_id失效。

2:临时素材media_id是可复用的。

如果是php5.3以下的版本path路径需要带上@,加文本绝对路径,5.3以上的版本需要用new curlFile()类获取绝对地址

  1. $path = new CURLFile(realpath('G:/xampp/htdocs/wx/app/zan.jpg'));
  2. $path = $path->name;//绝对路径
  3. $type = 'images';//thumb
  4. $res = $this->upload_media('image',$path);//获取到素材的media_id,有效期3天
  5. $media_id = $res->media_id;
  6. //以下是获取临时素材url
  7. $url = $this->get_media($media_id);//获取到临时素材的url
  8. public function upload_media($type,$path)
  9. {
  10. $url =
  11. 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=' .
  12. $this->get_access_token() . '&type=' . $type;
  13. $res = $this->upload($url, array('media' => '@'.$path));
  14. // 判断是否调用成功
  15. return $res;
  16. }
  17. public function get_media($media_id)
  18. {
  19. return
  20. 'https://api.weixin.qq.com/cgi-bin/media/get?access_token=' .
  21. $this->get_access_token() . '&media_id=' . $media_id;
  22. }
  23. /*
  24. * 上传图片。图文专用
  25. */
  26. public static function upload($url, $filedata) {
  27. $curl = curl_init ();
  28. if (class_exists ( '/CURLFile' )) {//php5.5跟php5.6中的CURLOPT_SAFE_UPLOAD的默认值不同
  29. curl_setopt ( $curl, CURLOPT_SAFE_UPLOAD, true );
  30. } else {
  31. if (defined ( 'CURLOPT_SAFE_UPLOAD' )) {
  32. curl_setopt ( $curl, CURLOPT_SAFE_UPLOAD, false );
  33. }
  34. }
  35. curl_setopt ( $curl, CURLOPT_URL, $url );
  36. curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, FALSE );
  37. curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, FALSE );
  38. if (! empty ( $filedata )) {
  39. curl_setopt ( $curl, CURLOPT_POST, 1 );
  40. curl_setopt ( $curl, CURLOPT_POSTFIELDS, $filedata );
  41. }
  42. curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
  43. $output = curl_exec ( $curl );
  44. curl_close ( $curl );
  45. return $output;
  46. }

相关推荐:

php微信开发之上传临时素材,php开发素材_PHP教程

微信上传临时素材实例代码

以上就是php微信获取临时素材的方法(附代码)的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行