Reading the contents of each file in an FTP directory using a single connection

My goal is to connect to an FTP account, read files in a specific folder, capture the contents and print it on the 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;
    }
}

This works well to get the file names with which I need to capture content. Then I want to overwrite through an array of file names and save the contents in a variable for further processing.

I'm not sure how to do this, I would suggest that it should be something like this:

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 to read a .txt file from an FTP server into a variable?

Although I do not like the idea of ​​connecting every time to capture the contents of the file, I would prefer to do this in the original instance.

+4
1

/ , ftp_get ($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);
}

( .)

+1

All Articles