在這里我們利用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.111cn.net); 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); ?>
