我目前正在尝试使用 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/