如何从ftp服务器获取文件并在自己的服务器上复制

时间:2019-02-14 09:46:48

标签: php file ftp

我想从客户端服务器获取文件并将其复制到我的服务器上,我已成功连接到客户端服务器,代码如下。

// connect and login to FTP server
$ftp_server = "xx.xxx.xxx.xxx";
$ftp_username = 'xxxxxxxxxxxxxxx';
$ftp_userpass = 'xxxxxxxxxxxxxxxx';
 $ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);
echo "<pre>";
 print_r($login);
  echo "</pre>";
 // get the file list for /
 $filelist = ftp_rawlist($ftp_conn, "/");

// close connection
ftp_close($ftp_conn);
echo "<pre>";
print_r($filelist);
echo "</pre>";
// output $filelist
var_dump($filelist);

任何人都可以建议我如何实现这一目标?

2 个答案:

答案 0 :(得分:0)

您可以使用此处指定的ftp_fget函数:http://php.net/manual/en/function.ftp-fget.php

  

(ftp_fget()从FTP服务器检索remote_file,并将其写入给定的文件指针。)

以下是文档提供的示例:

<?php

// path to remote file
$remote_file = 'somefile.txt';
$local_file = 'localfile.txt';

// open some file to write to
$handle = fopen($local_file, 'w');

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to download $remote_file and save it to $handle
if (ftp_fget($conn_id, $handle, $remote_file, FTP_ASCII, 0)) {
 echo "successfully written to $local_file\n";
} else {
 echo "There was a problem while downloading $remote_file to $local_file\n";
}

// close the connection and the file handler
ftp_close($conn_id);
fclose($handle);
?>

答案 1 :(得分:0)

这是我现在解决的方法,所有文件都将复制到您的服务器上。如果 ftp_ssl_connect 安全,请使用

$ftp_server = "xx.xxx.xxx.xxx";
$ftp_username = 'xxxxxxxxxxxxxx';
$ftp_userpass = 'xxxxxxxxxxxxxxxxxxx';

$ftp_conn = ftp_ssl_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);

ftp_pasv($ftp_conn,pasv);


$output_directory="files1/ftpgetfiles/137/";
// get the file list for /
$filelist = ftp_nlist($ftp_conn, "/");

foreach ($filelist as $key => $value) {
$fp = fopen($output_directory.$value,"w");
if(ftp_fget($ftp_conn, $fp, $value, FTP_BINARY))
{
    fclose($fp);
}
}

ftp_close($ftp_conn);
相关问题