PHP 尝试 FTPS 传输创建空文件

标签 php ssl ftp ftps

我目前正在尝试使用 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://{user}:{pass}@{host}:{port}"

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

最佳答案

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

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

}

关于PHP 尝试 FTPS 传输创建空文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3597875/

相关文章:

c# - 连接到 ftps ://URL

ruby-on-rails - 如何在 Ruby Net::FTP 中使用代理服务器?

ios - WhiteRaccoon iOS 4.2 错误

php - 使用带有 php 的 https 构建安全登录 require 或 include

c# - 使用 SSL/TLS 时出现 WCF 错误

php - 将 JSON 从 angular 2 发布到 php

cocoa-touch - 在 iOS 设备上运行的 SSL/TLS 服务器

ssl - 通过 SSL 的 JDBC 到缓存数据库

PHP/MySQL 联系人列表

javascript - 将 div 替换为另一个 if 语句