PHP使用curl請(qǐng)求實(shí)現(xiàn)post方式上傳圖片文件功能示例

在調(diào)用第三方api接口時(shí),有時(shí)會(huì)遇到通過http協(xié)議上傳圖片,以下是一個(gè)微信公眾平臺(tái)新增永久素材的例子(使用前請(qǐng)閱讀相關(guān)微信文檔);
php代碼:

/* 使用curl函數(shù) */
$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請(qǐng)求方式: 默認(rèn)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); /* //設(shè)置請(qǐng)求方式 */
      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請(qǐng)求 不驗(yàn)證證書和hosts
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 不從證書中檢查SSL加密算法是否存在
  }
  $response = curl_exec($ch);
  curl_close($ch);
  if(empty($response)){
    exit("錯(cuò)誤請(qǐng)求");
  }
  return $response;
}
function isPostHasFile($value)
{
  if (is_string($value) && strpos($value, '@') === 0 && is_file(realpath(ltrim($value, '@')))) {
    return true;
  }
  return false;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容