>  기사  >  백엔드 개발  >  POST 모드에서 이미지 파일을 업로드하기 위한 PHP 메소드 예제

POST 모드에서 이미지 파일을 업로드하기 위한 PHP 메소드 예제

小云云
小云云원래의
2018-03-02 11:06:404860검색

이 기사에서는 주로 post 메소드에서 PHP의 이미지 파일을 업로드하는 방법에 대한 예를 공유합니다. 타사 API 인터페이스를 호출할 때 때때로 http 프로토콜을 통해 이미지를 업로드하는 경우가 있습니다. 다음은 영구 추가의 예입니다.

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函数 */
$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;

관련 권장 사항:

사용자 이름 확인 및 jquery의 $.post 메서드의 전통적인 Ajax 구현을 설명하는 예 ,

ajax 비동기 요청 게시 방법

php는 인터페이스 요청 코드 예제

를 호출하는 게시 방법을 시뮬레이션합니다.

위 내용은 POST 모드에서 이미지 파일을 업로드하기 위한 PHP 메소드 예제의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.