tags:

views:

301

answers:

2

I'm writing an automation script on a production server that, among other things, needs to grab a list of remote files via FTP (FTP is the only option for interacting with the remote filesystem) and selectively download them.

Why I can't use PHP's native FTP wrappers

This is a production server in a very brittle environment. I'm writing it using PHP CLI, since most of the existing automation scripts are written this way. However, although I have a very new PHP 5.1.2 installation, I'm not able to recompile it with --with-ftp, and that option is not enabled.

The remaining options

So, my options are to connect, get my file list, and selectively download using shell_exec() or the php_filesystem functions using an FTP stream and the PHP native filesystem functions.

Unfortunately, I'm not able to find good code examples of either. When I try to shell_exec using FTP commands, the program hangs, presumably because control stays at the shell once I open up the FTP prompt.

$ftp_connect_command = "ftp -v -n $bl_ftp_host";
$ftp_login_command = "user $bl_ftp_user $bl_ftp_password";
$ftp_bye_command = "bye";

$ftp_connect_response = shell_exec("$ftp_connect_command");
// this never executes, because it hangs here waiting for a return to shell
$ftp_login_response = shell_exec($ftp_login_command);

Or, I imagine the stream based way to do this would be:

$ftp_path = "ftp://$bl_ftp_user:$bl_ftp_user@$bl_ftp_host/";
$stream_options = array('ftp' => array('overwrite' => false));
$context = stream_context_create();
if ($dh = opendir($ftp_path, $context))
{
    while (filename = readdir($dh))
    {
     print($filename);
    }
}

But I'm not sure if this is considered a reliable method.

Can anyone provide code samples showing how to capture a directory list and download files by either of these methods?

A: 

Have you looked at the native PHP FTP library? http://us2.php.net/ftp

Daniel A. White
I clarified in the question a little. I'm not able to recompile PHP in this case.
danieltalsky
+2  A: 

Apparently, wordpress uses pemftp for pure-PHP FTP (on systems compiled without FTP support)

Frank Farmer