2017-04-24 138 views
-1

我試圖從另一個域使用ftp_get和ftp_nlist獲取多個文件。 ftp_nlist期望的資源和一個字符串,但下面返回使用ftp_get和ftp_nlist通過FTP獲取多個文件

ftp_nlist()預計參數1是資源,在

提供的foreach

無效的參數(空給出)

<?php 
// Connect and login to FTP server 
$ftp_server = "hostname"; 
$ftp_username ="username"; 
$ftp_userpass = "password"; 
$includes = "/directory/"; 
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server"); 
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass); 

// Get file list 
    $contents = ftp_nlist($conn_id, $includes); 

// Loop through for file 1 
foreach ($contents as $file) { 
    $local_file = '/path/to/file.php'; 
    $server_file = '/path/to/file.php'; 
    ftp_get($conn_id, $local_file, $server_file, FTP_BINARY); 
} 

// Loop through for file 2 
foreach ($contents as $file) { 
    $local_file = '/path/to/file.php'; 
    $server_file = '/path/to/file.php'; 
    ftp_get($conn_id, $local_file, $server_file, FTP_BINARY); 
} 

// close connection 
ftp_close($ftp_conn); 
?> 

回答

2

變量$conn_id您傳遞給ftp_nlist()未定義。您需要通過$ftp_conn中的全部ftp_*函數代替。 (ftp_get()在你的情況)

檢查ftp_close()以及確保你沒有忘記關閉連接。

我建議使用ftp_功能的包裝,例如https://github.com/dg/ftp-php,以使調試更容易。你將能夠使用Exceptions並且像這樣捕獲它們:

try { 
    $ftp = new Ftp; 
    $ftp->connect($ftp_server); 
    $ftp->login($ftp_username, $ftp_userpass); 
    $ftp->nlist($includes); 

} catch (FtpException $e) { 
    echo 'Error: ', $e->getMessage(); 
} 
+0

公平點,謝謝。即使使用$ conn_id = ftp_connect($ ftp_server);定義,foreach循環仍然被視爲無效。有什麼想法嗎? – toomanyairmiles

+1

處理'ftp'時常見的解決方案是使用**被動模式**。嘗試添加'ftp_pasv($ conn_id,true);'在連接後立即執行 – wormi4ok

+1

如果仍然返回'false',請查看'error_get_last()'顯示的內容。 – wormi4ok

相關問題