情景:客戶端上傳圖片到服務器A,服務器A同步上傳至另外一個靜態資源服務器B
環境:php7 linux(ubuntu)
安裝php的ssh2擴展
sudo apt-get install libssh2-1-dev sudo apt-get install php-ssh2
sudo service apache2 restart
可在圖片上傳至服務器A后同步上傳至B
A上傳文件至B 函數
1 //scp上傳文件至遠程服務 $host為B服務器域名(IP) $user B服務器用戶 $password B服務器密碼 $local_file為本地文件, $remote_file為遠程文件 2 function scpUploadFile($host,$user,$password,$local_file,$remote_file){ 3 $ssh2 = ssh2_connect($host, 22); //先登陸SSH並連接 4 ssh2_auth_password($ssh2,$user,$password);//身份認證 也可以用 5 //本地傳輸文件到遠程服務器 6 $stream=ssh2_scp_send($ssh2, $local_file, $remote_file, 0777); 7 $data =['host'=>$host,'user'=>$user,'pass'=>$password,'lo'=>$local_file,'re'=>$remote_file]; 8 9 //默認權限為0644,返回值為bool值,true或false. 10 return $stream; 11 }
A從B下載文件 函數
1 function scpDownloadFile($host,$user,$password,$local_file,$remote_file){ 2 $ssh2 = ssh2_connect($host, 22); 3 ssh2_auth_password($ssh2,$user,$password); 4 //從遠程服務器下載文件 5 $stream=ssh2_scp_revc($ssh2, $remote_file, $local_file); 6 return $stream; 7 }
上述連接及身份認證方式 可換為SSH密鑰鏈接
1 $ssh2 = ssh2_connect('shell.example.com', 22, array('hostkey'=>'ssh-rsa')); 2 3 if (ssh2_auth_pubkey_file($connection, 'username', 4 '/home/username/.ssh/id_rsa.pub', 5 '/home/username/.ssh/id_rsa', 'secret')) { 6 echo "Public Key Authentication Successful\n"; 7 } else { 8 die('Public Key Authentication Failed'); 9 }
簡單處理客戶端多圖片上傳請求(處理粗糙,可自行完善)
多圖片上傳數組處理
1 function buildImgArray($_FILES){ 2 $i = 0; 3 foreach ($files as $v){//三維數組轉換成2維數組 4 if(is_string($v['name'])){ //單文件上傳 5 $info[$i] = $v; 6 $i++; 7 }else{ // 多文件上傳 8 foreach ($v['name'] as $key=>$val){//2維數組轉換成1維數組 9 //取出一維數組的值,然后形成另一個數組 10 //新的數組的結構為:info=>i=>('name','size'.....) 11 $info[$i]['name'] = $v['name'][$key]; 12 $info[$i]['size'] = $v['size'][$key]; 13 $info[$i]['type'] = $v['type'][$key]; 14 $info[$i]['tmp_name'] = $v['tmp_name'][$key]; 15 $info[$i]['error'] = $v['error'][$key]; 16 $i++; 17 } 18 } 19 } 20 return $info; 21 }
上傳至A並同步上傳至B
1 function uploadFile($files,$host,$user,$password,$maxSize=1048576,$imgFlag=true){ 2 $date = getdate(time()); 3 $year = $date['year']; 4 $mon = $date['mon']; 5 $day = $date['mday']; 6 $path = 'upload/'; 7 if (! is_dir($path)) { 8 mkdir($path,0777,true); 9 } 10 $i = 0; 11 foreach ($files as $val) { 12 if ($val['error'] == 0) { 13 if($val['size']>$maxSize){ 14 echo "文件太大了"; 15 return 1; 16 } 17 if($imgFlag){ 18 $result = getimagesize($val['tmp_name']); 19 if(!$result){ 20 echo "您上傳的不是一個真正圖片"; 21 return 2; 22 } 23 } 24 if(!is_uploaded_file($val['tmp_name'])){ 25 echo "不是通過httppost傳輸的"; 26 return 3; 27 } 28 $realName = $year.$mon.$day.time().$val['name']; 29 $destination = $path."/".$realName; 30 if(move_uploaded_file($val['tmp_name'], $destination)){ 31 $isUp = scpUploadFile($host,$user,$password,$destination,'/upload/'.$realName); 32 if(!$isUp){ 33 return 4; 34 } 35 $uploadedFiles[$i]['img']='/upload/'.$realName; 36 $i++; 37 } 38 }else { 39 echo '上傳失敗'; 40 return 5; 41 } 42 } 43 return $uploadedFiles; 44 }
