php把文件上传到远程服务器上例子
在这里我们利用curl实现把本地服务器的文件通过curl发送请求给远程服务器的php文件接受就实现了上传,还一个是利用ftp来上传方法也是php中的curl操作ftp服务器进行上传.
我这里写的是用curl的代码,本地代码如下:
- <?php
- header('content-type:text/html;charset=utf8');
- $curl = curl_init();
- $data = array('img'=>'@'. dirname(__FILE__).'/img/login.gif');
- curl_setopt($curl, CURLOPT_URL, "http://www.demo.com/uploadimg.php");
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($curl, CURLOPT_POST, true);
- curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
- $result = curl_exec($curl);
- curl_close($curl);
- echo json_decode($result);
- ?>
远程服务器接受端代码,代码如下:
- <?php
- if($_FILES)
- {
- $filename = $_FILES['img']['name'];
- $tmpname = $_FILES['img']['tmp_name'];
- if(move_uploaded_file($tmpname, dirname(__FILE__).'/img/'.$filename))
- {
- echo json_encode('上传成功');
- }
- else
- {
- $data = json_encode($_FILES);
- echo $data;
- }
- }
- ?>
例子,同样是利用curl不过这是利用ftp,代码如下:
- <?php
- $localfile = "php_homepage.txt";
- $fp = fopen ($localfile, "r");
- $arr_ip = gethostbyname(www.phpfensi.com);
- echo $arr_ip;
- $ftp = "ftp://".$arr_ip."/public_html/".$localfile;
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_VERBOSE, 1);
- curl_setopt($ch, CURLOPT_USERPWD, '***:****');
- curl_setopt($ch, CURLOPT_URL, $ftp);
- curl_setopt($ch, CURLOPT_PUT, 1);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_INFILE, $fp);
- curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
- $http_result = curl_exec($ch);
- $error = curl_error($ch);
- echo $error."<br>";
- $http_code = curl_getinfo($ch ,CURLINFO_HTTP_CODE);curl_close($ch);
- fclose($fp);
- ?>