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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章