使用php将多个文件上传到远程FTP服务器

时间:2013-07-16 17:19:59

标签: php file upload ftp

我需要使用php上传到ftp服务器4个文件。我有以下示例代码,我正在使用它。如何更改此代码以上载服务器上已有的多个文件(在ftp传输时未上传)。

假设我在子文件夹中有4个文件相对于执行上传的php文件,让我们调用子文件夹“/ fileshere /”,其中包含以下4个文件:

file1.zip file2.zip file3.zip file4.zip

我需要脚本上传每个文件,然后发出完成消息。

以下是我正在使用并尝试改编的起始代码。任何帮助将不胜感激:

$ftp_server = "ftp.yourserver.com";
$ftp_user_name = "ftpuser";
$ftp_user_pass = "ftppassword";
$remote_dir = "/target/folder/on/ftp/server";

// 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);

//default values
$file_url = "";

if($login_result) {
//set passive mode enabled
ftp_pasv($conn_id, true);

//check if directory exists and if not then create it
if(!@ftp_chdir($conn_id, $remote_dir)) {
//create diectory
ftp_mkdir($conn_id, $remote_dir);
//change directory
ftp_chdir($conn_id, $remote_dir);
}

$file = $_FILES["file"]["tmp_name"];
$remote_file = $_FILES["file"]["name"];

$ret = ftp_nb_put($conn_id, $remote_file, $file, FTP_BINARY, FTP_AUTORESUME);
while(FTP_MOREDATA == $ret) {
$ret = ftp_nb_continue($conn_id);
}

if($ret == FTP_FINISHED) {
echo "File '" . $remote_file . "' uploaded successfully.";
} else {
echo "Failed uploading file '" . $remote_file . "'.";
}
} else {
echo "Cannot connect to FTP server at " . $ftp_server;
}

1 个答案:

答案 0 :(得分:1)

试试此代码

<?php
// connect and login data
$web = 'www.website.com';
$user = 'admin';
$pass = 'password';
// file location
$server_file = '/public_html/example.txt';
$local_file = 'example.txt';
//connect
$conn_id = ftp_connect($web);
$login_result = ftp_login($conn_id,$user,$pass);
//uploading
if (ftp_put($conn_id, $server_file, $local_file, FTP_BINARY))
 {echo "Success";} 
else {echo "Failed";}
?>

如果你想上传多个文件,只需将你的文件名放入数组中,然后将整个代码放入for循环中。