创建PHP并将其上载到FTP服务器而不保存本地

Dre*_*hie 8 php ftp

我在连接我工作的两个不同进程时遇到问题.我的任务是从数据库中提取数据,从数据创建文件,然后将其上传到FTP服务器.

到目前为止,我使用此代码创建和下载文件,$out是一个包含完整文本文件的字符串:

if ($output == 'file')
{
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Length: ".strlen($out));
    header("Content-type: application/txt");
    header("Content-Disposition: attachment; filename=".$file_name);
    echo($out);
}
Run Code Online (Sandbox Code Playgroud)

当我想在浏览器中运行脚本并下载文件时,这可以工作,但我希望将其发送到FTP服务器.

我知道我与FTP服务器的连接工作正常,我正确导航到正确的目录,我从磁盘上取文件并将它们放在FTP上使用ftp_put(),但我想把$out它写下来直接作为$filenameFTP服务器上的名称文件.我可能误解的事情,但是当我试图ftp_put和ftp_fput,它似乎是他们想要的文件位置,而不是文件流.我可以考虑不同的功能吗?

mat*_*tei 17

我已在这里回答而不是评论,因为评论忽略了代码格式.

你可以尝试:


$fp = fopen('php://temp', 'r+');
fwrite($fp, $out);
rewind($fp);       
ftp_fput($ftp_conn, $remote_file_name, $fp, FTP_ASCII);

这将创建一个临时流而不实际将其写入磁盘.我不知道其他任何方式


Bog*_*nio 7

以下是matei的解决方案,作为完整函数ftp_file_put_contents():

function ftp_file_put_contents($remote_file, $file_string) {

// FTP login details
$ftp_server='my-ftp-server.de'; 
$ftp_user_name='my-username'; 
$ftp_user_pass='my-password';

// Create temporary file
$local_file=fopen('php://temp', 'r+');
fwrite($local_file, $file_string);
rewind($local_file);       

// FTP connection
$ftp_conn=ftp_connect($ftp_server); 

// FTP login
@$login_result=ftp_login($ftp_conn, $ftp_user_name, $ftp_user_pass); 

// FTP upload
if($login_result) $upload_result=ftp_fput($ftp_conn, $remote_file, $local_file, FTP_ASCII);

// Error handling
if(!$login_result or !$upload_result)
{
    echo('<p>FTP error: The file could not be written to the FTP server.</p>');
}

// Close FTP connection
ftp_close($ftp_conn);

// Close file handle
fclose($local_file); }


// Function call
ftp_file_put_contents('my-file.txt', 'This text will be written to your text file via FTP.');
Run Code Online (Sandbox Code Playgroud)