Houdmont
Houdmont

Reputation: 1323

Downloading a gunzipped file over FTP

I am attempting to download a gunzipped file from an FTP server.

It appears to download successfully (correct file size, etc) but when I extract the contents, it fails stating that the data-format is violated.

If I manually download the same file using an FTP client like FileZilla, and then extract it, the extract works, which means my PHP for downloading the file is incorrect somehow.

Here is my code:

$this->_file = 'data.csv.gz';
$this->_directory = DOC_ROOT.'/imports/';

private function _loadFromFtpDataSource($url=null,$username=null,$password=null) {
    try {
        $conn_id = ftp_connect($url);
        $login_result = ftp_login($conn_id, $username, password);
        ftp_pasv($conn_id, true);
        $handle = fopen($this->_directory . $this->_file, "w");
        ftp_fget($conn_id, $handle, $this->_file, FTP_ASCII, 0);            
        ftp_close($conn_id);
        fclose($handle);
    } catch (Exception $e) {
        $this->status = false;
        error_log("Failed to connect to ftp server");
    }
}

Can anyone see any reason why it may not be downloading correctly? Does special attention need to be taken when downloading a gunzipped file over FTP?

Upvotes: 0

Views: 817

Answers (3)

Utku Yıldırım
Utku Yıldırım

Reputation: 2277

Binary files need to download in binary mode not ascii mode

$this->_file = 'data.csv.gz';
$this->_directory = DOC_ROOT.'/imports/';

private function _loadFromFtpDataSource($url=null,$username=null,$password=null) {
    try {
        $conn_id = ftp_connect($url);
        $login_result = ftp_login($conn_id, $username, password);
        ftp_pasv($conn_id, true);
        $handle = fopen($this->_directory . $this->_file, "w");
        ftp_fget($conn_id, $handle, $this->_file, FTP_BINARY, 0);            
        ftp_close($conn_id);
        fclose($handle);
    } catch (Exception $e) {
        $this->status = false;
        error_log("Failed to connect to ftp server");
    }
}

Upvotes: 1

Lars
Lars

Reputation: 5799

If the file does not use purely ASCII (e.g. UTF-8 instead), your download will most likely get corrupted. If you change the mode from FTP_ASCII to FTP_BINARY, you should be alright.

Upvotes: 1

Marek Sebera
Marek Sebera

Reputation: 40681

Try changing this line:

ftp_fget($conn_id, $handle, $this->_file, FTP_ASCII, 0);

to

ftp_fget($conn_id, $handle, $this->_file, FTP_BINARY, 0);

you're transfering binary data archive (...when I extract the contents...) not a text file
read more on
http://www.coreftp.com/docs/web1/Ascii_vs_Binary_transfers.htm

Upvotes: 2

Related Questions