从FTP获取自动下载文件的PHP类
/** * 从FTP获取自动下载文件的PHP类 * @author yukar ( http://yukar.iteye.com ) */ class FtpClass{ private $ftpObj; private $ftpHost = "****"; // 服务器地址 private $ftpPort = ****; // 服务器端口 private $ftpUser = "****"; // 用户名 private $ftpPassword = "****"; // 口令 private $localBase = '/your/save/path'; //你存放的目录 function __construct($initData=array()){ if (isset($initData['ftpHost']) && $initData['ftpHost']){ $this->ftpHost = $initData['ftpHost']; } if (isset($initData['ftpPort']) && $initData['ftpPort']){ $this->ftpPort = $initData['ftpPort']; } if (isset($initData['ftpUser']) && $initData['ftpUser']){ $this->ftpUser = $initData['ftpUser']; } if (isset($initData['ftpPassword']) && $initData['ftpPassword']){ $this->ftpPassword = $initData['ftpPassword']; } if (isset($initData['localBase']) && $initData['localBase']){ $this->localBase = $initData['localBase']; } } function ftp_connect(){ if(!$this->ftpObj){ $this->ftpObj = ftp_connect($this->ftpHost,$this->ftpPort); // 连接ftp服务器 if($this->ftpObj) { if(ftp_login($this->ftpObj, $this->ftpUser, $this->ftpPassword)) { // 登录 return true; }else{ return false; } }else { return false; } } } function ftp_download_file($fileName) { //获取FTP路径 $ftpPath = dirname($fileName) . "/"; //获取文件名 $selectFile = basename($fileName); // 进入指定路径 if(@ftp_chdir($this->ftpObj,$ftpPath)) { //$localBase 如果不存在,新创建目录,务必确保 有创建权限 if(!is_dir($this->localBase)){ mkdir($this->localBase, 0777); } $toFile = $this->localBase.$fileName; if(ftp_get($this->ftpObj, $toFile, $selectFile, FTP_BINARY)) { //下载指定的FTP文件到指定的本地文件 return true; }else { return false; } }else { return false; } } function ftp_quit(){ if($this->ftpObj){ ftp_quit($this->ftpObj); } } }调用就更简单了
$ftpObj = new FtpClass(); $ftpObj->ftp_connect(); $filename = '/config/config.sample.php'; $ftpObj->ftp_download_file($filename); $ftpObj->ftp_quit(); exit();