2010-12-02 261 views
12

我很好奇如何使用PHP通過FTP上傳文件。比方說,我有上傳表單和用戶上傳了一個文件。如何將文件(無需從臨時目錄移動)傳輸到使用PHP的某個FTP主機?使用PHP通過FTP上傳文件

回答

18

在這裏你去:處理略去了

$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 :-) 

錯誤。

13

下面是一個代碼示例

$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); 
+1

你的縮進怎麼了? – jwueller 2010-12-02 13:24:31

+1

對不起,現在好了 – 2010-12-02 13:40:39

3

這裏有一個函數來爲你做它。

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"); 
2

如何通過捲曲上傳? (注意:你也可以使用curl作爲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:[email protected]/'.$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.'; 
} 

?>