반응형
필요한 서버에 sftp로 폴더 업로드 소스
개인적으로 사실 요즘 잘 안쓰긴 하다만... 그래도 예전에 네이버에 작성했던 글을 다시 읽으며 코드를 다시 보는게 재밌긴하다.
$strServer = $host;
$strServerPort = $port;
$strServerUsername = $username;
$strServerPassword = $pw;
$resConnection = ssh2_connect($strServer, $strServerPort);
if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword))
{
$sftp = ssh2_sftp($resConnection);
$dir = ssh2_exec($resConnection,"pwd");
stream_set_blocking($dir, true);
$stream_out = ssh2_fetch_stream($dir, SSH2_STREAM_STDIO);
$remote_folder = stream_get_contents($stream_out);
$local_folder = "/home/";
$remote_folder = trim($remote_folder);
// The sftp path to upload
$remotePath = str_replace($local_folder,$remote_folder."/",$filepath);
$res = $this->lib_mpas->uploadSftp($filepath,$remotePath,$sftp);
if($res){
ssh2_exec($resConnection, 'exit');
return true;
}else{
ssh2_exec($resConnection, 'exit');
$result = array(
"status"=>"error",
"msg"=>"해당 폴더의 파일생성권한이없습니다."
);
echo json_encode($result);
exit;
}
}
이 코드를 사용하려면 당연하지만 접속서버의 정보를 모두 알아야한다. id, pwd, ip 등등
서버쪽에서 인증서 인증방식으로 설정하여 접근방식도 있으니 그 부분이 보안상? 으로는 더 안전 할 듯 싶다.
간단히 설명하자면
$local_folder 를 원격서버의 $remote_folder 로 업로드 하는것이며
업로드 담당코드는 사실
$this->lib_mpas->uploadSftp($filepath,$remotePath,$sftp);
이 라이브러리 안에 있다.
당연하게도 php에 ssh2 가 깔려있어야한다.
uploadSftp 함수
public function uploadSftp( $local,$remote,$resource)
{
// Get the directory of the uploaded file
$dir = dirname($remote);
// Determine whether the uploaded directory exists
$is_dir = $this->sftp_is_dir($dir,$resource);
if(!$is_dir){
// The directory does not exist, create a directory
$this->sftp_mkdir($dir,$resource);
}
return copy($local,'ssh2.sftp://'.$resource.$remote);
}
/**
* Create sftp directory
* @param $dir
*/
public function sftp_mkdir($dir,$resource) // Use create directory loop
{
ssh2_sftp_mkdir($resource, $dir,0777,true);
}
/**
* Check if the directory exists
* @param $dir
* @return bool
*/
public function sftp_is_dir($dir,$resource){
return file_exists('ssh2.sftp://'.$resource.$dir);
}
소스 자체는 간단한데
접근하려는 폴더가 없으면 777로 생성하고 파일을 copy 로 옮기는 것이다.폴더 생성 권한이 반드시 필요하며 생성시 접근권한을 777이 아닌 다른권한으로 설정해도된다.
해당 소스는 예를들어 /home/example/test.txt 파일 하나를 sftp로 업로드 하는 소스이니 폴더 안에 여러 파일을 올리고싶다면 for문을 사용하면 된다.
#주의점
해당 코드에 ip 및 id와 pwd 가 모두 들어있기에 외부에 노출되면 안된다.
접근하는 아이디가 원격서버에서 쓰기권한이 있어야지 정상적으로 진행된다.
옮기려는 로컬파일에 읽기권한이 있어야한다.
반응형
'php > 코드이그나이터(CI3)' 카테고리의 다른 글
파일다운로드 (0) | 2024.05.12 |
---|---|
파일업로드 (0) | 2024.05.12 |
php exec 실행안될때 확인 (0) | 2024.05.12 |
코드이그나이터3, 세션생성오류 (0) | 2024.04.18 |
php 서버내의 폴더, 파일 압축 (0) | 2024.04.18 |