代码之家  ›  专栏  ›  技术社区  ›  Wilhelm Murdoch

PHP尝试FTPS传输时会创建空文件

  •  0
  • Wilhelm Murdoch  · 技术社区  · 14 年前

    我目前正在尝试使用PHP在我们的服务器和远程FTPS(FTP over SSL)服务器之间传输小文件。我是完成这件事的标准集市,例如,文件内容,文件内容,等等。。。具有以下流上下文:

    stream_context_create(array('ftp' => array('overwrite' => true), 'ssl' => array('allow_self_signed' => true)))
    

    我使用以下代码传递这个上下文流。它可以很好地连接到FTPS服务器,但是在创建远程文件时,文件本身完全是空的。文件大小为0时为空。

        if(false === file_exists($localFile))
        {
            throw new Exception("Local file, {$localFile}, does not exist.");
        }
    
        if(false === $localFileContents = file_get_contents($localFile))
        {
            throw new Exception("Could not open Local file, {$localFile}.");
        }
    
        if(false === file_put_contents("{$this->url}{$remoteFile}", $localFileContents, FILE_APPEND, $this->context))
        {
            throw new Exception("Could not write to remote file, {$remoteFile}.");
        }
    

    我们目前使用的是Windows/Apache安装程序,所以如果不编译我们自己的PHP二进制文件,我就不能使用ftp\u ssl\u connect()。我们无论如何不能走这条路,因为这是我们环境的一个重大变化。

    3 回复  |  直到 7 年前
        1
  •  1
  •   Drew    11 年前

    我不得不做一些非常相似的事情。

    http://www.php.net/manual/en/function.curl-setopt.php#90988

    最后我把它包在了一个班级里:

    class ftps {
    
        /**
         * @param string $remoteDir Fully quantified path to the directory, eg ftp://foo:bar@blergh.com/directory/
         */
        public function ls($remoteDir) {
    
            $connection = $this->initConnection();
    
            curl_setopt_array($connection, array(
                CURLOPT_URL => $remoteDir,
                CURLOPT_RETURNTRANSFER => 1
            ));
    
            $result = curl_exec($connection);
    
            $this->finishConnection($connection);
    
            return explode("\n", $result);
    
        }
    
        private function initConnection()
        {
            $connection = curl_init();
    
            curl_setopt_array($connection, array(
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_FTP_SSL => CURLFTPSSL_TRY
            ));
    
            return $connection;
        }
    
        private function finishConnection(&$connection)
        {
            curl_close($connection);
            unset($connection);
        }
    
    }
    
        2
  •  1
  •   shamittomar    14 年前

    这个 PHP FTP/FTPS Documentations 说:


    从PHP5.0.0开始,可以通过ftp://URL包装器附加文件。在以前的版本中,尝试通过ftp://附加到文件将导致失败。

    您确定使用的是PHP>=5.0.0吗。或者你也可以试试 FILE_TEXT 标记而不是 FILE_APPEND

        3
  •  1
  •   halfer    7 年前

    只是对所选答案中的代码进行了更正:

        CURLOPT_URL => $remoteDir,
        CURLOPT_RETURNTRANSFER => 1