无法使用FTP和PHP连接服务器


Unable to connect a server with FTP and PHP

当我通过PHP代码连接FTP服务器时,我无法连接到它。最尴尬的是,当我试图用ftp_connect()方法连接服务器时,只得到false。未报告任何错误。这是我第一次在PHP中使用FTP。如果以前做过这方面工作的人能在这里帮我的话。这是我的代码:

/* Source File Name and Path */    
$remote_file = $_SERVER['DOCUMENT_ROOT'] ."/some-folder/file.txt";
/* New file name and path for this file */
$ftp_host = 'ftp://targetserver.com/some folder/'; 
$ftp_user_name = 'user';
$ftp_user_pass = 'XXXXX';
/* New file name and path for this file */
$local_file = 'ftp://targetserver.com/some-folder/file.txt';
/* Connect using basic FTP */
$connect_it = ftp_connect( $ftp_host, 21);
var_dump($connect_it);
/* Login to FTP */
$login_result = ftp_login( $connect_it, $ftp_user_name, $ftp_user_pass );
/* Download $remote_file and save to $local_file */
if ( ftp_get( $connect_it, $local_file, $remote_file, FTP_BINARY ) ) {
     echo "Successfully written to $local_file'n";
}
else {
    echo "There was a problem'n";
}
/* Close the connection */
ftp_close( $connect_it );

实际上得到false意味着您的ftp客户端由于某种原因无法连接到服务器

$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");

在深入php调试之前,最好先尝试另一个ftp客户端,例如https://filezilla-project.org/看看是否一切都很好,如果不是,你会节省时间,因为问题不是来自php脚本。

更新1

然后试试这个:

$ftp_host = 'targetserver.com';

http://php.net/manual/en/function.ftp-connect.php#refsect1-函数.ftp-连接参数

The FTP server address. This parameter shouldn't have any trailing slashes and shouldn't be prefixed with ftp://.

至于local_file和remote_file,它们必须是路径,而不是urlhttp://php.net/manual/en/function.ftp-get.php#refsect1-函数.ftp-get-examples

由于ftp_connect函数没有产生错误,我认为扩展已经安装。这很可能是防火墙问题,端口21被阻塞。(这是一个非常常见的原因)

<html>
  <body>
    <form enctype="multipart/form-data" action="upload_file.php" method="POST">
      <input type="hidden" name="MAX_FILE_SIZE" value="100000" />
      Choose a file to upload: <input name="uploadedfile" type="file" /><br />
      <input type="submit" value="Upload File" />
    </form>
  </body>
</html>
<?php
$ftp_server = "94.23.x.xxx";
$ftp_username   = "anxxxxx";
$ftp_password   =  "6xxxxxxxx";
// setup of connection
$conn_id = ftp_connect($ftp_server) or die("could not connect to $ftp_server");
// login
if (@ftp_login($conn_id, $ftp_username, $ftp_password))
{
  echo "conectd as $ftp_username@$ftp_server'n";
}
else
{
  echo "could not connect as $ftp_username'n";
}
$file = $_FILES["uploadedfile"]["name"];
$remote_file_path = "/JustForTest".$file;
ftp_put($conn_id, $remote_file_path, $_FILES["uploadedfile"]["tmp_name"],
        FTP_ASCII);
ftp_close($conn_id);
echo "'n'nconnection closed";
?>

那么上面的代码有什么问题呢?