通过FTP下载枪械文件

时间:2011-11-18 09:13:25

标签: php ftp gzip gunzip

我正在尝试从FTP服务器下载枪械文件。

它似乎成功下载(正确的文件大小等),但是当我提取内容时,它无法说明数据格式被违反。

如果我使用像FileZilla这样的FTP客户端手动下载相同的文件,然后将其解压缩,则提取工作正常,这意味着我下载文件的PHP不正确。

这是我的代码:

$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");
    }
}

任何人都可以看到为什么它可能无法正确下载?通过FTP下载枪械文件时是否需要特别注意?

3 个答案:

答案 0 :(得分:2)

尝试更改此行:

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

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

您正在传输二进制数据存档(...when I extract the contents...)而不是文本文件 阅读更多关于
http://www.coreftp.com/docs/web1/Ascii_vs_Binary_transfers.htm

答案 1 :(得分:1)

如果文件不使用纯ASCII(例如UTF-8),则下载很可能会被破坏。如果将模式从FTP_ASCII更改为FTP_BINARY,则应该没问题。

答案 2 :(得分:1)

二进制文件需要以binary模式而不是ascii模式

下载
$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");
    }
}