파일을 다른 서버로 전송하기 위해 꼭 FTP 나 fopen 으로만 가능한 것은 아닙니다. cUrl 함수로도 FTP의 기능을 충분히 대체할 수 있는데, 파일을 일반 변수로 전송할 수 있습니다.

로컬에서 파일을 받아 http://example.com/test.php 로 파일을 전송하는데, $_FILES 변수가 아닌 $_POST 의 imagefile 변수로 받는다는 점에 주목해야 합니다.

<?php 
/* 
test.php 의 내용 
print_r($_POST); 

// 내용을 임시 파일로 만들어서 uploaded 폴더에 저장합니다. 
$str = base64_decode($_POST['imagefile']); 
$tmpfname = tempnam("/tmp", "test_");  
$handle = fopen($tmpfname, "wb");  
fwrite($handle, $str);  
fclose($handle);  

move_uploaded_file($tmpfname, "uploaded/test.gif"); 
*/ 

if($_FILES) 
{ 
  $filename = $_FILES['userfile']['tmp_name']; 
  $handle = fopen($filename, "r"); 
  $data = base64_encode(fread($handle, filesize($filename))); 

  // $data is file data 
  $post   = array('imagefile' => $data); 
  $timeout = 30; 
  $curl    = curl_init(); 

  curl_setopt($curl, CURLOPT_URL, 'http://example.com/test.php'); 
  curl_setopt($curl, CURLOPT_TIMEOUT, $timeout); 
  curl_setopt($curl, CURLOPT_POST, 1); 
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
  curl_setopt($curl, CURLOPT_POSTFIELDS, $post); 

  $str = curl_exec($curl); 

  curl_close ($curl); 
  print_r($str); 
  /* 
  결과: 
  Array ( 
    [imagefile] => /9j/4AAQSkZJRgABAgEAYABgAAD/7gAOQWRv.... 
  )  
  */ 
} 
?> 

<form enctype="multipart/form-data" action="" method="POST">  
    이 파일을 전송합니다: <input name="userfile" type="file" />  
    <input type="submit" value="파일 전송" />  
</form>

0 댓글