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 uploading it to an FTP server.
So far, I have the file being created and downloadable using this code, $out
being a string that contains the complete text file:
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);
}
This works when I want to just run the script in a browser and download the file, but I'm looking to instead send it to an FTP server.
I know my connection to the FTP server is working just fine, and I'm correctly navigating to the correct directory, and I've taken files from disk and put them on the FTP using ftp_put()
, but I'm looking to take $out
and write it directly as a file with $filename
as its name on the FTP server. I may be misreading things, but when I tried ftp_put
and ftp_fput
, it seemed that they want file locations, not file streams. Is there a different function I could consider?
The easiest solution is using
file_put_contents
with FTP URL wrapper: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 thephp://temp
(or thephp://memory
) stream:(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.
Here is matei's solution from above as complete function ftp_file_put_contents():
I've answered here instead of the comments since comments ignore code formatting.
you could try:
this will create a temporary stream without actually writing it to disk. I don't know any other way
Actually ftp_put expects the path to the local file (as a string), so try to write the data in a temporary file and then ftp_put it to the server
In this case you don't need to send the headers you were sending in your example.