2015-06-16 161 views
0

我在PHP這樣的功能:PHP FTP上傳功能

function UploadFileToFTP($local_path, $remote_path, $file, $filename) { 
    global $settings; 

    $remote_path = 'public_html/'.$remote_path; 

    $ftp_server = $settings["IntegraFTP_H"]; 
    $ftp_user_name = $settings["IntegraFTP_U"]; 
    $ftp_user_pass = $settings["IntegraFTP_P"]; 

    //first save the file locally 
    file_put_contents($local_path.$filename, $file); 

    //login 
    $conn_id = ftp_connect($ftp_server); 
    ftp_pasv($conn_id, true); 
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 

    // check connection 
    if((!$conn_id) || (!$login_result)) { 
     echo "FTP connection has failed!"; 
    } 

    //change directory 
    ftp_chdir($conn_id, $remote_path); 
    $upload = ftp_put($conn_id, $filename, $local_path.$filename, FTP_BINARY); 

    // check upload status 
    if(!$upload) { 
     echo "FTP upload has failed!"; 
    } 
    // close the FTP stream 
    ftp_close($conn_id); 
} 

我在這裏把它稱爲:

UploadFileToFTP('p/website/uploaded_media/', 'media/', $_FILES["file"]["tmp_name"], $filename); 

所選文件被移動到本地目錄,也被上傳但是到FTP該文件由於沒有正確上傳而變得腐敗。

我怎樣才能正確地上傳文件?

回答

0

當需要上傳文件到PHP它存儲在一個臨時位置上傳的文件,位置存儲在$_FILES["file"]["tmp_name"]

然後,您將該值作爲變量$file傳遞到您的UploadToFTP函數中。

然後試圖保存上傳的文件的副本:

//first save the file locally 
file_put_contents($local_path.$filename, $file); 

這將完成的是寫包含在$file字符串(即臨時文件的路徑)到您的新位置 - 但你想要寫文件的內容。

而不是使用file_put_contents使用move_uploaded_file的:

move_uploaded_file($file, $local_path.$filename);