PHP PHP 使用 Curl 函数模拟文件上传功能

kerr · 2019-01-07 20:27:55 · 热度: 12

功能代码如下:

/**
 * 上传文件
 * @param $url      文件上传地址
 * @param $file     文件路径,如:/tmp/codercto.csv
 * @param $mime     文件 mine type 值,如:text/csv
 * @return array|string
 */
public function uploadFile($ur, $file, $mime)
{
    $data['file_name'] = new \CURLFile($file, $mime);
    $handle = curl_init();
    curl_setopt($handle, CURLOPT_URL, $url);
    curl_setopt ($handle, CURLOPT_POST, TRUE);
    curl_setopt ($handle, CURLOPT_POSTFIELDS, $data);
    curl_setopt ($handle, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, FALSE);
    $output = curl_exec($handle);
    $code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
    $error = curl_error($handle);
    $errno    = curl_errno($handle);
    curl_close($handle);

    if($code != 200 || $errno!=0)
    {
        return [
            "ret"=>$code,
            "error"=>$error,
            "errno"=>$errno,
        ];
    }

    $output = json_decode($output, 1);
    return $output;
}

猜你喜欢:
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册