2015-06-16 163 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);