php POST 图片到远程服务器

2022-09-11 12:21:58 浏览数 (1)

代码语言:javascript复制
 /**
     * POST 图片到远程服务器
     * 
     * @param string $uri 请求的url地址
     * @param array $params 格外参数
     * custom 额外参数
     * ['file' => '文件路径', 'mime' => '文件类型', 'postname' => "上传的文件名称",'custom' => ['key' => value]]
     *
     * @return mixed
     */
    public static function getUploadFile($uri, $params = [])
    {
        if (isset($params['postname']) && isset($params['file'])) {
            if (class_exists('CURLFile')) {
                $chFile = new CURLFile(realpath($params['file']));
                $chFile->mime = isset($params['mime']) ? $params['mime'] : getimagesize($params['file'])['mime'];
                $chFile->postname = $params['postname'];
                $data['file'] = $chFile;
            } else {
                $data['file'] = "@" . realpath($params['file']) . ";type={$params['mime']}";
            }
            if (isset($params['custom']) && !empty($params['custom'])) {
                $custom = $params['custom'];
                while ($row = current($custom)) {
                    $key = key($custom);
                    $data[$key] = $row;
                    next($custom);
                }
            }
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $uri);
            curl_setopt($ch, CURLOPT_POST, 1);//post方式
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            $output = curl_exec($ch);
            curl_close($ch);
            return $output;
        }
        return false;
    }

0 人点赞