我正在尝试使用PHP连接ftp,这就是我的功能
private function ftpConnect() {
$this->ftpConn = ftp_connect($this->ftp["server"]);
$ftpLogin = ftp_login($ftpConn, $this->ftp["user"], $this->ftp["pass"]);
// check connection
if ((!$this->ftpConn) || (!$ftpLogin)) {
echo "Connection Failed!\n";
}
}
但我得到warnig“Undefined variable:ftpConn”和“Warning:ftp_login()期望参数1是资源,null给定”。
我做错了什么?
答案 0 :(得分:1)
这是我之前做过的事情,也许是它的一些兴趣。
<?php
/**
* A simple FTP helper class
*/
Class ftp{
public $status;
function __construct($host, $user, $pass){
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->status = 'Ready';
}
private function connect(){
if (!isset($this->ftp)){
$this->ftp = ftp_connect($this->host, 21, 3) or die ("Cannot connect to host");
ftp_login($this->ftp, $this->user, $this->pass) or die("Cannot login, wrong username or password");
ftp_pasv($this->ftp, true);
$this->status = 'Connected';
}
}
public function ftp_get_contents($ftp_path, $local_file){
$this->connect();
if(ftp_get($this->ftp, $local_file, $ftp_path, FTP_BINARY)) {
$this->status = 'Download complete';
}else{
$this->status = 'Cannot download';
}
}
public function ftp_put_contents($local_file, $ftp_path){
$this->connect();
if(ftp_put($this->ftp, $ftp_path, $local_file, FTP_BINARY)) {
$this->status = 'Upload complete';
}else{
$this->status = 'Cannot upload';
}
}
public function ftp_delete_file($ftp_path){
$this->connect();
if (ftp_delete($this->ftp, $ftp_path)) {
$this->status = "$ftp_path deleted successfully";
}else{
$this->status = "Could not delete $ftp_path";
}
}
public function ftp_make_dir($dir){
$this->connect();
if (ftp_mkdir($this->ftp, $dir)) {
$this->status = "Successfully created $dir";
} else {
$this->status = "Could not create $dir";
}
}
public function ftp_delete_dir($dir){
$this->connect();
if (ftp_rmdir($this->ftp, $dir)) {
$this->status = "Successfully deleted $dir";
} else {
$this->status = "Could not delete $dir";
}
}
public function show_files($dir='/'){
$this->connect();
return ftp_nlist($this->ftp, $dir);
}
private function close(){
ftp_close($this->ftp);
}
function __destruct(){
if(isset($this->ftp)){
$this->close();
}
}
}
?>
使用示例:
<?php
$ftp = new ftp('ftp.example.com', 'user', 'pass');
echo '<pre>'.print_r($ftp->show_files(), true).'</pre>';
?>