Example of PHP Uploading Picture File in post Mode Using curl Request

  • 2021-10-24 19:07:17
  • OfStack

This article describes the example of PHP using curl request to achieve post upload picture file function. Share it for your reference, as follows:

When calling the third-party api interface, we sometimes encounter uploading pictures through http protocol. The following is an example of adding permanent materials to a WeChat public platform;

php code:


/*  Use curl Function  */
$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 Request mode :  Default 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'])) {
          /*  Support file upload  */
          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); /* // Set the request mode  */
      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 Request   Do not verify certificates and hosts
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //  Do not check from certificate SSL Does an encryption algorithm exist 
  }
  $response = curl_exec($ch);
  curl_close($ch);
  if(empty($response)){
    exit(" Bad request ");
  }
  return $response;
}
function isPostHasFile($value)
{
  if (is_string($value) && strpos($value, '@') === 0 && is_file(realpath(ltrim($value, '@')))) {
    return true;
  }
  return false;
}

You can also use the built-in system functions of php. If there are problems in using it, it is recommended to check whether the corresponding system functions are enabled.

Use exec System functions:


/*  Use exec Function  */
$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'  => ' There is an error in WeChat official account service, please contact the administrator ',
  );
}
return $params;

Use system System functions:


/*  Use system Function  */
$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'  => ' There is an error in WeChat official account service, please contact the administrator ',
    );
  }
}
return $params;

For more readers interested in PHP related contents, please check the topics of this site: "php curl Usage Summary", "PHP Network Programming Skills Summary", "PHP Array (Array) Operation Skills Encyclopedia", "php String (string) Usage Summary", "PHP Data Structure and Algorithm Tutorial" and "json Format Data Operation Skills Summary in PHP"

I hope this article is helpful to everyone's PHP programming.


Related articles: