使用PHP通过FTP上传文件

时间:2010-12-02 12:58:25

标签: php file-upload ftp

我很好奇如何使用PHP通过FTP上传文件。假设我上传表单,用户上传了一个文件。如何使用PHP将文件(不从临时目录移动)传输到某个FTP主机?

7 个答案:

答案 0 :(得分:24)

你走了:

$ftp = ftp_connect($host,$port,$timeout);
ftp_login($ftp,$user,$pass);

$ret = ftp_nb_put($ftp, $dest_file, $source_file, FTP_BINARY, FTP_AUTORESUME);

while (FTP_MOREDATA == $ret)
    {
        // display progress bar, or someting
        $ret = ftp_nb_continue($ftp);
    }

// all done :-)

为简洁起见,省略了错误处理。

答案 1 :(得分:15)

这是一个代码示例

 $ftp_server="";
 $ftp_user_name="";
 $ftp_user_pass="";
 $file = "";//tobe uploaded
 $remote_file = "";

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

 // upload a file
 if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
    echo "successfully uploaded $file\n";
    exit;
 } else {
    echo "There was a problem while uploading $file\n";
    exit;
    }
 // close the connection
 ftp_close($conn_id);

答案 2 :(得分:6)

这是为你做的功能。

function uploadFTP($server, $username, $password, $local_file, $remote_file){
    // connect to server
    $connection = ftp_connect($server);

    // login
    if (@ftp_login($connection, $username, $password)){
        // successfully connected
    }else{
        return false;
    }

    ftp_put($connection, $remote_file, $local_file, FTP_BINARY);
    ftp_close($connection);
    return true;
}

用法:

uploadFTP("127.0.0.1", "admin", "mydog123", "C:\\report.txt", "meeting/tuesday/report.txt");

答案 3 :(得分:6)

如何通过Curl上传? (注意:您也可以使用curl for SFTP,FTPS)

<?php

$ch = curl_init();
$localfile = '/path/to/file.zip';
$remotefile = 'filename.zip';
$fp = fopen($localfile, 'r');
curl_setopt($ch, CURLOPT_URL, 'ftp://ftp_login:password@ftp.domain.com/'.$remotefile);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
curl_exec ($ch);
$error_no = curl_errno($ch);
curl_close ($ch);
if ($error_no == 0) {
    $error = 'File uploaded succesfully.';
} else {
    $error = 'File upload error.';
}

?>

答案 4 :(得分:2)

查看PHP网站上的FTP section - 这非常有帮助。

答案 5 :(得分:0)

FTP密码必须用单引号引起来,否则它将不接受特殊字符

$ftp_server="";
$ftp_user_name="";
$ftp_user_pass=''; // this is the right way 
$file = "";//tobe uploaded
$remote_file = "";

答案 6 :(得分:0)

对于任何想在进行文件传输时显示上传进度的人来说,这是一个不错的php-ftp-client库:

代码

$interval = 1;
$ftp->asyncDownload('illustrations/assets.zip', 'assets.zip', function ($stat) use ($interval) {
    ob_end_clean();
    ob_start();

    echo sprintf(
        "speed : %s KB/%ss | percentage : %s%% | transferred : %s KB | second now : %s <br>",
        $stat['speed'],
        $interval,
        $stat['percentage'],
        $stat['transferred'],
        $stat['seconds']
    );

    ob_flush();
    flush();
}, true, $interval);

在浏览器中显示结果:

enter image description here