2010-04-20 9 views
5

내가 작업 한 두 개의 다른 프로세스를 연결하는 데 문제가 있습니다. 데이터베이스에서 데이터를 가져 와서 데이터에서 파일을 만든 다음 FTP 서버에 업로드하는 작업을했습니다. 난 그냥 브라우저에서 스크립트를 실행하고자 할 때로컬로 저장하지 않고 PHP로 파일을 작성하고 FTP 서버에 업로드

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); 
} 

이 작동 :

지금까지, 나는 전체 텍스트 파일이 포함 된 문자열되고, $out를이 코드를 사용하여 생성되는 파일을 다운로드 할 수 있습니다 파일을 다운로드하지만 대신 FTP 서버로 보내려고합니다.

FTP 서버에 대한 연결이 정상적으로 작동하고 있으며 올바른 디렉토리로 이동 중이며 디스크에서 파일을 가져 와서 ftp_put()을 사용하여 FTP에 저장했지만 찾고 있습니다. $out을 가져 와서 FTP 서버의 이름으로 $filename이라는 파일로 직접 작성하십시오. 내가 잘못 읽은 것일 수도 있지만, ftp_putftp_fput을 시도했을 때 파일 스트림이 아닌 파일 위치를 원한 것처럼 보였습니다. 고려할 수있는 다른 기능이 있습니까?

답변

14

주석은 코드 서식을 무시하기 때문에 주석 대신 여기서 대답했습니다.

당신은 시도 할 수 :

 

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

이 실제로 디스크에 작성하지 않고 임시 스트림을 생성합니다. 나는 다른 방법

+0

그게 내가 바라는거야, 고마워. –

3

사실 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_put 다음과 임시 파일에 데이터를 작성하려고 기대 당신의 예에서 보낸 헤더를 보내야합니다.

+1

파일 시스템에 파일을 만들지 않고이를 수행 할 수있는 방법이 있습니까? –

4

여기에 완전한 기능 ftp_file_put_contents() 위에서 matei's 솔루션입니다 모르겠어요

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.'); 
0

가장 쉬운 해결책은 사용을 file_put_contentsFTP URL wrapper와 :

file_put_contents('ftp://username:pa‌​[email protected]/path/to/file', $out); 

이 경우, 작동하지 않는 이유는 아마도 URL wrappers enabled in PHP이 없기 때문일 것입니다. 당신이 쓰는 더 잘 제어 (전송 모드, 수동 모드, 오프셋, 읽기 제한 등)이 필요한 경우


php://temp (or the php://memory) stream에 대한 핸들로 ftp_fput를 사용

$conn_id = ftp_connect('hostname'); 

ftp_login($conn_id, 'username', 'password'); 

$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); 

(추가 오류 처리)

관련 문제