PHP uploading file from browser to FTP

2019-06-04 18:25发布

问题:

I want to upload files from user's machine to folder uploads in my FTP and it doesn't work. Can you help me?

$ftp_server = "some ip";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, "some name", "some password");

$target_dir = "uploads/";
$target_file = basename($_FILES["filename"]["name"]);

if (ftp_fput($ftp_conn, $target_dir.$target_file, FTP_ASCII))
  {
  echo "Successfully uploaded $target_file.";
  }
else
  {
  echo "Error uploading $target_file.";
  }

回答1:

You need to specify what local file (as of the webserver) you want to upload to the FTP server.

You can retrieve a name of a temporary file that contains a file uploaded via HTTP POST from user's machine to your webserver using $_FILES["filename"]["tmp_name"]. Read about POST method uploads in PHP.

You can then pass that to ftp_put (no need for ftp_fput):

ftp_put($ftp_conn, $target_dir.$target_file, $_FILES["filename"]["tmp_name"], FTP_IMAGE)

Two other issues in your code (which are not your immediate problems, but you will face them right after you resolve it):

  • Absolutely do not use FTP_ASCII, if you are uploading binary files, like .mp3. Use FTP_IMAGE.

  • You need to use ftp_pasv.



回答2:

use php-ftp-client library:

$ftp = new \FtpClient\FtpClient();
$ftp->connect($host, true, 990);
$ftp->login($login, $password);
// upload with the BINARY mode
$ftp->putAll($source_directory, $target_directory);

// Is equal to
$ftp->putAll($source_directory, $target_directory, FTP_BINARY);

// or upload with the ASCII mode
$ftp->putAll($source_directory, $target_directory, FTP_ASCII);


标签: php ftp upload