How can I check when ftp_pasv must be used?

679 Views Asked by At

Like discussed in this question, I've a problem with ftp_fget to download a file from FTP when I'm in my local development environment :

Warning: ftp_fget(): Opening BINARY mode data connection for myFile.csv

As suggested, use ftp_pasv($conn_id, TRUE); is working very well, but I don't want to use the FTP passive mode when I'm on my production server.

How can I check when ftp_pasv must be used ?

I tried this :

<?php

    $conn_id = ftp_connect(FTP_SERVER, FTP_PORT, 30);

    $handle = fopen(dirname(__FILE__).'/data/temp.csv', 'w');

    if (ftp_fget($conn_id, $handle, FTP_FILENAME, FTP_BINARY, 1)) {
          copy($handle,dirname(__FILE__).'/data/myFile.csv');
    }
    else {
        // Try with passive mode
        ftp_pasv($conn_id, TRUE);
        if (ftp_fget($conn_id, $handle, FTP_FILENAME, FTP_BINARY, 1)) {
            copy($handle,dirname(__FILE__).'/data/myFile.csv');
        }
        else {
            echo "Error downloading the file";
        }
    }

    ftp_close($conn_id);

But it gives me :

Warning: ftp_fget(): Data connection unexpectedly closed, file transfer /myFile.csv aborted by client.

1

There are 1 best solutions below

0
On

You cannot check that. It's basically a part of the session information (along with host name, user name, and password) that you need to know upfront.

Though obviously as there are only two modes, you can try one and fallback to the other, if the first fails.

I'd try the passive first (as that tends to work more often) and fallback to the active.