4

My goal is to connect to an FTP account, read the files in a particular folder, grab the content and list out to my screen.

This is what I have:

// set up basic connection
$conn_id = ftp_connect('HOST_ADDRESS');

// login with username and password
$login_result = ftp_login($conn_id, 'USERNAME', 'PASSWORD');

if (!$login_result)
{
    exit();
}

// get contents of the current directory
$contents = ftp_nlist($conn_id, "DirectoryName");

$files = [];

foreach ($contents AS $content)
{
    $ignoreArray = ['.','..'];
    if ( ! in_array( $content , $ignoreArray) )
    {
        $files[] = $content;
    }
}

The above works well to get the file names I need to grab the content from. Next I want to recurse through the filename array and store the content into a variable for further processing.

I am not sure how to do this, I would imagine it would need to be something like this though:

foreach ($files AS $file )
{
    $handle = fopen($filename, "r");
    $contents = fread($conn_id, filesize($file));
    $content[$file] = $contents;
}

The above idea comes from here:
PHP: How do I read a .txt file from FTP server into a variable?

Although I don't like the idea of having to connect each time to grab the file contents, would prefer to do it on the initial instance.

Community
  • 1
  • 1
HappyCoder
  • 5,985
  • 6
  • 42
  • 73

1 Answers1

1

To avoid having to connect/login for every file, use the ftp_get and reuse your connection ID ($conn_id):

foreach ($files as $file)
{
    // Full path to a remote file
    $remote_path = "DirectoryName/$file";
    // Path to a temporary local copy of the remote file
    $temp_path = tempnam(sys_get_temp_dir(), "ftp");
    // Temporarily download the file
    ftp_get($conn_id, $temp_path, $remote_path, FTP_BINARY);
    // Read the contents of temporary copy
    $contents = file_get_contents($temp_path);
    $content[$file] = $contents;
    // Discard the temporary copy
    unlink($temp_path);
}

(You should add some error checking.)

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
  • ok - thank you. So if I wanted to keep the file I would just not use: unlink? – HappyCoder Mar 23 '15 at 08:33
  • Sure, but in that case you probably want to use a more meaningful file and path like `$temp_path = "/path/".$file`. And the `$temp_path` variable name would be confusing too. – Martin Prikryl Mar 23 '15 at 09:14