有同学需要使用SSL+FTP的方式加密传输文件。希望我给封装一个东西,需求就是可以上传文件(PUT)和远端改名(RENAME)就行。
我开始以为SSL+FTP = SFTP,后来发现这个想法好像是错误的。SFTP是跑在SSH协议上面的FTP,而FTPs就像https一样是跑在SSL协议上面的FTP。
示例程序使用了ftp_ssl_connect函数。源代码如下:
#! /bin/php <?php if($argc!=8){ echo "Usage:/n"; echo "/t$argv[0] put host port user pass local_file remote_file/n"; echo "/t$argv[0] rename host port user pass old_name new_name/n"; return -1; } $host = $argv[2]; $port = $argv[3]; $user = $argv[4]; $pass = $argv[5]; //connect to sftp $ftps = ftp_ssl_connect($host,$port,10) or die("ERROR:Couldn't connect to $host"); if(@ftp_login($ftps, $user, $pass)){ ftp_pasv($ftps,TRUE); if($argv[1]== 'put'){ //upload local file $local_file = $argv[6]; $remote_file = $argv[7]; if(ftp_put($ftps,$remote_file,$local_file,FTP_BINARY)){ echo "PUT Successed./n"; }else{ echo "PUT Failed./n"; } }else if($argv[1] == 'rename'){ //rename remote file $old_name = $argv[6]; $new_name = $argv[7]; if(ftp_rename($ftps,$old_name,$new_name)){ echo "RENAME Successed./n"; }else{ echo "RENAME Failed./n"; } } ftp_close($conn_id); }else{ echo "ERROR:Couldn't login/n"; } ?>
附注:如果使用ftp_ssl_connect函数,需要php支持OpenSSL和FTP才行。