1. 程式人生 > >php怎麼使用curl傳輸檔案流

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