Maison  >  Article  >  développement back-end  >  Exemple de méthode PHP pour télécharger des fichiers image en mode POST

Exemple de méthode PHP pour télécharger des fichiers image en mode POST

小云云
小云云original
2018-03-02 11:06:404860parcourir

Cet article partage principalement avec vous un exemple de méthode de téléchargement de fichiers image en PHP en mode POST Lors de l'appel de l'interface API tierce, vous rencontrerez parfois le téléchargement d'images via le protocole HTTP. ajout de matériaux permanents à la plateforme publique WeChat ;

code 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;
    }

Vous pouvez également utiliser les fonctions système intégrées de PHP. Si des problèmes surviennent lors de l'utilisation, c'est le cas. Il est recommandé de vérifier si les fonctions système correspondantes sont activées.

Utilisez la fonction système 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;

Utilisez la fonction système système :

/* 使用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;

Recommandations associées :

Explication de implémentation ajax avec exemples La tradition de vérification du nom d'utilisateur et la méthode $.post de jquery ,

méthode de publication de demande asynchrone ajax

php simule la publication méthode pour appeler la requête d'interface Exemple de code

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn