[英]Creating and uploading a file in PHP to an FTP server without saving locally
我在連接我工作的兩個不同進程時遇到問題。 我的任務是從數據庫中提取數據,從數據創建文件,然后將其上傳到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);
}
當我想在瀏覽器中運行腳本並下載文件時,這可以工作,但我希望將其發送到FTP服務器。
我知道我與FTP服務器的連接工作正常,我正確導航到正確的目錄,我已經從磁盤上取文件並使用ftp_put()
將它們放在FTP上,但我希望采取$out
並將其直接寫為FTP $filename
名為$filename
。 我可能誤讀了一些東西,但當我嘗試ftp_put
和ftp_fput
,似乎他們想要文件位置,而不是文件流。 我可以考慮不同的功能嗎?
我已在這里回答而不是評論,因為評論忽略了代碼格式。
你可以嘗試:
$fp = fopen('php://temp', 'r+');
fwrite($fp, $out);
rewind($fp);
ftp_fput($ftp_conn, $remote_file_name, $fp, FTP_ASCII);
這將創建一個臨時流而不實際將其寫入磁盤。 我不知道其他任何方式
以下是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.');
實際上ftp_put需要本地文件的路徑(作為字符串),所以嘗試將數據寫入臨時文件然后ftp_put到服務器
file_put_contents('/tmp/filecontent'.session_id(), $out);
ftp_put($ftp_conn, $remote_file_name, '/tmp/filecontent'.session_id());
unlink('/tmp/filecontent'.session_id());
在這種情況下,您無需發送示例中發送的標頭。
最簡單的解決方案是使用帶有FTP URL包裝器的 file_put_contents
:
file_put_contents('ftp://username:password@hostname/path/to/file', $out);
如果它不起作用,可能是因為您沒有在PHP中啟用URL包裝器 。
如果您需要更好地控制寫入(傳輸模式,被動模式,偏移,讀取限制等),請使用帶有php://temp
(或php://memory
)流句柄的ftp_fput
:
$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);
(添加錯誤處理)
或者您可以直接在FTP服務器上打開/創建文件。 如果文件很大,這個特別有用,因為你不會將整個內容保存在內存中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.