情景:客户端上传图片到服务器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 函数
//scp上传文件至远程服务 $host为B服务器域名(IP) $user B服务器用户 $password B服务器密码 $local_file为本地文件, $remote_file为远程文件
function scpUploadFile($host,$user,$password,$local_file,$remote_file){
$ssh2 = ssh2_connect($host, 22); //先登陆SSH并连接
ssh2_auth_password($ssh2,$user,$password);//身份认证 也可以用
//本地传输文件到远程服务器
$stream=ssh2_scp_send($ssh2, $local_file, $remote_file, 0777);
$data =['host'=>$host,'user'=>$user,'pass'=>$password,'lo'=>$local_file,'re'=>$remote_file];
//默认权限为0644,返回值为bool值,true或false.
return $stream;
}
A从B下载文件 函数
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密钥链接
$ssh2 = ssh2_connect('shell.example.com', 22, array('hostkey'=>'ssh-rsa'));
if (ssh2_auth_pubkey_file($connection, 'username',
'/home/username/.ssh/id_rsa.pub',
'/home/username/.ssh/id_rsa', 'secret')) {
echo "Public Key Authentication Successful\n";
} else {
die('Public Key Authentication Failed');
}
简单处理客户端多图片上传请求(处理粗糙,可自行完善)
多图片上传数组处理
function buildImgArray($_FILES){
$i = 0;
foreach ($files as $v){//三维数组转换成2维数组
if(is_string($v['name'])){ //单文件上传
$info[$i] = $v;
$i++;
}else{ // 多文件上传
foreach ($v['name'] as $key=>$val){//2维数组转换成1维数组
//取出一维数组的值,然后形成另一个数组
//新的数组的结构为:info=>i=>('name','size'.....)
$info[$i]['name'] = $v['name'][$key];
$info[$i]['size'] = $v['size'][$key];
$info[$i]['type'] = $v['type'][$key];
$info[$i]['tmp_name'] = $v['tmp_name'][$key];
$info[$i]['error'] = $v['error'][$key];
$i++;
}
}
}
return $info;
}
上传至A并同步上传至B
function uploadFile($files,$host,$user,$password,$maxSize=1048576,$imgFlag=true){
$date = getdate(time());
$year = $date['year'];
$mon = $date['mon'];
$day = $date['mday'];
$path = 'upload/';
if (! is_dir($path)) {
mkdir($path,0777,true);
}
$i = 0;
foreach ($files as $val) {
if ($val['error'] == 0) {
if($val['size']>$maxSize){
echo "文件太大了";
return 1;
}
if($imgFlag){
$result = getimagesize($val['tmp_name']);
if(!$result){
echo "您上传的不是一个真正图片";
return 2;
}
}
if(!is_uploaded_file($val['tmp_name'])){
echo "不是通过httppost传输的";
return 3;
}
$realName = $year.$mon.$day.time().$val['name'];
$destination = $path."/".$realName;
if(move_uploaded_file($val['tmp_name'], $destination)){
$isUp = scpUploadFile($host,$user,$password,$destination,'/upload/'.$realName);
if(!$isUp){
return 4;
}
$uploadedFiles[$i]['img']='/upload/'.$realName;
$i++;
}
}else {
echo '上传失败';
return 5;
}
}
return $uploadedFiles;
}