簡體   English   中英

無法連接服務器與 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 );

實際為假意味着您的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/zh/function.ftp-connect.php#refsect1-function.ftp-connect-parameters

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

對於local_file和remote_file,它們必須是路徑,而不是url http://php.net/manual/en/function.ftp-get.php#refsect1-function.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";

?>

那么上面的代碼有什么問題呢?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM