php如何CURL 上传文件到其他服务器
今天想用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
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。