php怎么使用curl传输文件流

public function postFile()
{

   $name = 'filename';
   $path = './Resource/temp_pdf/';
   $ext = '.pdf';

   if (is_file($path . $name . $ext) && filesize($path . $name . $ext) != 0) {
      $url = "http://test.api.com/index.php";
      $post_data = array(
         "foo" => "bar",
         //@代表此字段属于文件,接收方只需用$_FILES便可接收文件
         "upload" => '@' . $path . $name . $ext,
      );

      $res = httpRequest($url,$post_data);

      var_dump($res);

      //TODO::获取返回数据的动作
   }


}



/**
 * 请求远程地址
 *
 * @param string $url 请求url
 * @param mixed $postFields 请求的数据
 * @param string $referer 来源网址
 * @param integer $timeOut 请求超时时间
 * @param array $header 头部文件
 * @return mixed 错误返回false,正确返回获取的字符串
 * @author fengxu
 */
function httpRequest($url, $postFields = null, $referer = null, $timeOut = 300, $header = null)
{
    if (empty($url) || !preg_match("#https?://[\w@\#$%*&=+-?;:,./]+#i", $url)) {
        return false;
    }
    $isPost = empty($postFields) ? false : true;

    $ch = curl_init();

    if (is_null($header)) {
        $header = array(
            'Pragma' => 'no-cache',
            'Accept' => 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,q=0.5',
            'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36',
        );
    }

    $headers = array();
    foreach ($header as $k => $v) {
        $headers[] = $k . ': ' . $v;
    }

    curl_setopt($ch, CURLOPT_URL, $url);
    if ($isPost) {
        //$postFields = http_build_query($postFields);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    }

    curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $response = curl_exec($ch);
    if ($response === false) {
        throw new Exception(curl_error($ch), '500');
    }
    return $response;
}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值