php代码:
/* 使用curl函数 */ $url = https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=access_token&type=image; $post_data = array( 'media' => '@bag03.jpg', ); $response = curl_http($url, 'post', $post_data); $params = array(); $params = json_decode($response,true); if (isset($params['errcode'])) { echo error: . $params['errcode']; echo msg : . $params['errmsg']; exit; } var_dump( $params ); /** * http请求方式: 默认get */ function curl_http($url, $method=get, $postfields){ $ch = curl_init(); curl_setopt($ch, curlopt_ssl_verifypeer, false); curl_setopt($ch, curlopt_returntransfer, true); curl_setopt($ch, curlopt_url, $url); switch ($method) { case post: curl_setopt($ch, curlopt_post, true); if (!empty($postfields)) { $hadfile = false; if (is_array($postfields) && isset($postfields['media'])) { /* 支持文件上传 */ if (class_exists('\curlfile')) { curl_setopt($ch, curlopt_safe_upload, true); foreach ($postfields as $key => $value) { if (isposthasfile($value)) { $postfields[$key] = new \curlfile(realpath(ltrim($value, '@'))); $hadfile = true; } } } elseif (defined('curlopt_safe_upload')) { if (isposthasfile($value)) { curl_setopt($ch, curlopt_safe_upload, false); $hadfile = true; } } } $tmpdatastr = (!$hadfile && is_array($postfields)) ? http_build_query($postfields) : $postfields; curl_setopt($ch, curlopt_postfields, $tmpdatastr); } break; default: curl_setopt($ch, curlopt_customrequest, $method); /* //设置请求方式 */ break; } $ssl = preg_match('/^https:\/\//i',$url) ? true : false; curl_setopt($ch, curlopt_url, $url); if($ssl){ curl_setopt($ch, curlopt_ssl_verifypeer, false); // https请求 不验证证书和hosts curl_setopt($ch, curlopt_ssl_verifyhost, false); // 不从证书中检查ssl加密算法是否存在 } $response = curl_exec($ch); curl_close($ch); if(empty($response)){ exit(错误请求); } return $response; } function isposthasfile($value) { if (is_string($value) && strpos($value, '@') === 0 && is_file(realpath(ltrim($value, '@')))) { return true; } return false; }
也可以使用php内置的系统函数,如果使用过程中出现问题,建议查看是否启用相应的系统函数。
使用exec系统函数:
/* 使用exec函数 */ $command = 'curl -f media=@'.$filepath.' https://api.weixin.qq.com/cgi-bin/media/upload?access_token=access_token&type=image'; $retval = array(); exec($command, $retval, $status); $params = array(); $params = json_decode($retval[0],true); if ($status != 0) { $params = array( 'errcode' => '-100', 'errmsg' => '公众号服务出错,请联系管理员', ); } return $params;
使用system系统函数:
/* 使用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;
相关推荐:
实例讲解ajax实现用户名校验的传统和jquery的$.post方式、
ajax异步请求post方式
php模拟post方式调用接口请求代码实例
以上就是php实现以post方式上传图片文件的方法实例的详细内容。
