Frage

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?

War es hilfreich?

Lösung

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

Andere Tipps

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.

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");
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top