Creating and uploading a file in PHP to an FTP server without saving locally

前端 未结 4 1625
感动是毒
感动是毒 2020-12-08 23:55

I\'m having a problem connecting two different processes that I have working. I\'ve been tasked with pulling data out of a database, creating a file from the data, and then

4条回答
  •  不思量自难忘°
    2020-12-09 00:37

    The easiest solution is using file_put_contents with FTP URL wrapper:

    file_put_contents('ftp://username:pa‌​ssword@hostname/path/to/file', $out);
    

    If it does not work, it's probably because you do not have URL wrappers enabled in PHP.


    If you need greater control over the writing (transfer mode, passive mode, offset, reading limit, etc), use the ftp_fput with a handle to the php://temp (or the php://memory) stream:

    $conn_id = ftp_connect('hostname');
    
    ftp_login($conn_id, 'username', 'password');
    ftp_pasv($conn_id, true);
    
    $h = fopen('php://temp', 'r+');
    fwrite($h, $out);
    rewind($h);
    
    ftp_fput($conn_id, '/path/to/file', $h, FTP_BINARY, 0);
    
    fclose($h);
    ftp_close($conn_id);
    

    (add error handling)


    Or you can open/create the file directly on the FTP server. That's particularly useful, if the file is large, as you won't have keep whole contents in memory.

    See Generate CSV file on an external FTP server in PHP.

提交回复
热议问题