php http文件上傳的實(shí)現(xiàn)方法:1、初始化cURL會(huì)話;2、獲取CURLFile實(shí)例;3、執(zhí)行給定的cURL會(huì)話;4、根據(jù)文件路徑獲取一個(gè)CURLFile類實(shí)例;5、設(shè)置保存的文件夾即可。
本文操作環(huán)境:windows7系統(tǒng)、PHP7.1版,DELL G3電腦
php http文件上傳如何實(shí)現(xiàn)?
PHP 利用CURL(HTTP)實(shí)現(xiàn)服務(wù)器上傳文件至另一服務(wù)器
代碼如下:
// 上傳端 /** * 向目標(biāo)地址推送xls文件 * @Date 2019/4/29 */ public function putXls() { // 目標(biāo)接口 $url = "http://xxx"; // 初始化 cURL 會(huì)話, 如果提供url,CURLOPT_URL 選項(xiàng)將會(huì)被設(shè)置成這個(gè)值 $ch = curl_init($url); // 獲取CURLFile實(shí)例 $xlsCurlFile = $this->makeCurlFile(base_path()."/public/tby.xls"); $data = array('xls' => $xlsCurlFile); // TRUE 時(shí)會(huì)發(fā)送 POST 請求,類型為:application/x-www-form-urlencoded,是 HTML 表單提交時(shí)最常見的一種。 curl_setopt($ch, CURLOPT_POST, 1); // 從 PHP 5.5.0 開始, @ 前綴已被廢棄,文件可通過 CURLFile 發(fā)送。 設(shè)置 CURLOPT_SAFE_UPLOAD 為 TRUE 可禁用 @ 前綴發(fā)送文件,以增加安全性。 curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // 執(zhí)行給定的 cURL 會(huì)話 // 成功時(shí)返回 TRUE, 或者在失敗時(shí)返回 FALSE。 然而,如果 設(shè)置了 CURLOPT_RETURNTRANSFER 選項(xiàng),函數(shù)執(zhí)行成功時(shí)會(huì)返回執(zhí)行的結(jié)果,失敗時(shí)返回 FALSE 。 $result = curl_exec($ch); if (curl_errno($ch)) {// 返回錯(cuò)誤代碼或在沒有錯(cuò)誤發(fā)生時(shí)返回 0 (零)。 // 返回錯(cuò)誤信息,或者如果沒有任何錯(cuò)誤發(fā)生就返回 '' (空字符串)。 $result = curl_error($ch); } // 關(guān)閉 cURL 會(huì)話 curl_close($ch); } /** * 根據(jù)文件路徑獲取一個(gè)CURLFile類實(shí)例 * @param string $file 文件路徑 * @return CURLFile * @Date 2019/4/29 */ private function makeCurlFile(string $file) { /** * .xls mime為 application/vnd.ms-excel * .xlsx mime為 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet * 可參考 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types * * 注意:也可以使用 finfo類動(dòng)態(tài)獲取,但需要裝fileinfo擴(kuò)展 * demo: $result = new finfo(); if (is_resource($result) === true) { return $result->file($filename, FILEINFO_MIME_TYPE); } return false; */ $mime = "application/vnd.ms-excel"; $info = pathinfo($file); $name = $info['basename']; $output = new CURLFile($file, $mime, $name); return $output; } // 接收端 public function getFile(){ // 保存的文件夾,需要注意所在用戶組是否有寫入權(quán)限 $uploads_dir = base_path()."/public/test"; $xlsFiles = $_FILES["xls"] ?? null; if($xlsFiles){ if ($xlsFiles["error"] == UPLOAD_ERR_OK) { $tmp_name = $xlsFiles["tmp_name"]; $name = $xlsFiles["name"]; move_uploaded_file($tmp_name, "$uploads_dir/$name"); } // todo success }else{ // todo fail }}
推薦學(xué)習(xí):《PHP視頻教程》