首页 文章

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

提问于
浏览
0

我目前正在尝试使用PHP在我们的服务器和远程FTPS(FTP over SSL)服务器之间传输小文件 . 我是完成这项工作的标准公平,即file_put_contents,file_get_contents等...以及以下流上下文:

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

远程文件位置,即$ this-> url,采用以下格式:“ftps:// @

我们目前正在使用Windows / Apache设置,所以我不能在不编译自己的PHP二进制文件的情况下使用ftp_ssl_connect() . 无论如何我们无法走这条路,因为这是我们环境的重大变化 .

3 回答

  • 1

    我只需要做一些非常相似的事情 .

    我在这里找到了解决方案: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);
        }
    
    }
    
  • 1

    PHP FTP/FTPS Documentations说:

    注意:附加自PHP 5.0.0文件可以通过ftp:// URL包装器追加 . 在以前的版本中,尝试通过ftp://附加到文件将导致失败 .

    您确定使用的是PHP> = 5.0.0 . 或者您可以使用 FILE_TEXT 标志而不是 FILE_APPEND 进行尝试 .

  • 1

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

    第11和第12行应为:

    CURLOPT_URL => $remoteDir,
        CURLOPT_RETURNTRANSFER => 1
    

相关问题