php如何CURL 上傳檔案到其他伺服器
阿新 • • 發佈:2019-02-10
今天想用php curl上傳檔案到別的伺服器,百度了下找到一個方法,
$ch = curl_init();
$data = array('name' => 'Foo', 'file' => '@/home/vagrant/test.png');
curl_setopt($ch, CURLOPT_URL, 'http://localhost/test/curl/load_file.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
但是這種方法死活不行,找了半天才發現這種方法自php5.5之後就已經廢棄了。
從
PHP 5.5.0 開始, @ 字首已被廢棄,檔案可通過 CURLFile 傳送。 設定 CURLOPT_SAFE_UPLOAD
為 TRUE
可禁用 @ 字首傳送檔案,以增加安全性。
遂使用 CURLFile 類得以解決。
具體實現程式碼如下(我封裝了一個方法來實現):
/** * 上傳頭像 */ function uploadFace(){ $file = request()->file('file')->getInfo(); if($file){ $upload = array( 'get_name' => 'file', 'type' => $file['type'], 'name'=> $file['name'], 'file' => $file['tmp_name'], ); exit(json_encode($this->connect('user/face', array('username' => input('username')), 'POST', $upload))); }else{ $this->dump('上傳圖片失敗#1'); } }
/** * 請求資料 * @param $action * @param array $params * @param string $type* @param $upload * @return mixed */ protected function connect($action, $params = array(), $type = 'POST', $upload = false){ $data = array(); $method = strtoupper($type); $url = $this->api_url . $action; $params['api_key'] = $this->api_key; if($method == 'GET'){ $url = "{$url}?" . http_build_query($params); } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); if($method == 'POST'){ if($upload){ //設定上傳檔案 $file = new \CURLFile($upload['file'], $upload['type'], $upload['name']); $params[$upload['get_name']] = $file; } curl_setopt($ch, CURLOPT_POSTFIELDS, $params); } $result = curl_exec($ch); curl_close($ch); if($data === null){ $this->dump('請求資料失敗.', 2); }else{ try{ $data = json_decode($result, true); }catch(\Exception $e){ $this->dump('parse error.', 2, $e); } } return $data; }
參考文獻:
http://php.net/manual/zh/class.curlfile.php