如何使用ftp_put在PHP中上传文件?

时间:2019-05-29 04:43:21

标签: php ftp

提交表单后,我尝试使用ftp_put上传文件。但是我的代码无法按预期工作:

$ftpHost   = '192.168.180.36';
$ftpUsername = 'userdownload';
$ftpPassword = 'Toms!';
$filepath = "C://xampp/htdocs/Helpdesk/fmt/download";
$connId = ftp_connect($ftpHost,21) or die("Couldn't connect to $ftpHost");
$ftpLogin = ftp_login($connId, $ftpUsername, $ftpPassword);

$file_name = $_FILES['file']['name'][$i];
$tmp_name = $_FILES['file']['tmp_name'][$i];
// try to upload file
if(ftp_put($connId, $file_name, $filepath.'/'.$file_name, FTP_BINARY)){
    echo "File transfer successful - $file_name";
}else{
    echo "There was an error while uploading $file_name";
}       

我收到此错误消息:

  

上传$ file_name时出错

1 个答案:

答案 0 :(得分:0)

我在您的代码中注意到了两件事。第一个是传输方式,具体取决于您的文件类型.ascii /文本文件扩展名列表中的文件以ascii传输,所有其他文件都以二进制传输。第二个可能是您的文件有问题您收到的文件可能是黑色的,请先检查一下。您可以尝试使用此代码,它对我有用。

  <?php
    // connect and login to FTP server
    $ftp_server = "ftp.example.com";
    $ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
    $login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);

    $file = "localfile.txt";

    // upload file
    if (ftp_put($ftp_conn, "serverfile.txt", $file, FTP_ASCII))
      {
      echo "Successfully uploaded $file.";
      }
    else
      {
      echo "Error uploading $file.";
      }
    // close connection
    ftp_close($ftp_conn);
    ?>