PHP에서 FTP 서버에서 파일 다운로드하는 방법은 무엇인가요?


PHP에서 FTP 서버에서 파일을 다운로드하는 방법은 다음과 같습니다.

1. FTP 함수 사용

PHP는 FTP 함수를 제공하여 FTP 서버와 상호 작용할 수 있습니다. ftp_get() 함수를 사용하여 FTP 서버에서 파일을 다운로드할 수 있습니다. 다음은 ftp_get() 함수를 사용하여 파일을 다운로드하는 예제입니다.

$ftp_server = "ftp.example.com";
$ftp_username = "username";
$ftp_password = "password";
$local_file = "local_file.txt";
$server_file = "/remote_file.txt";

// 연결 설정
$conn_id = ftp_connect($ftp_server);

// 로그인
$login_result = ftp_login($conn_id, $ftp_username, $ftp_password);

// 파일 다운로드
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
    echo "파일이 성공적으로 다운로드되었습니다.";
} else {
    echo "파일 다운로드에 실패했습니다.";
}

// 연결 종료
ftp_close($conn_id);

2. cURL 사용

cURL은 PHP에서 FTP 서버와 통신하는 데 사용할 수 있는 라이브러리입니다. curl 명령어를 사용하여 FTP 서버에서 파일을 다운로드할 수 있습니다. 다음은 cURL을 사용하여 파일을 다운로드하는 예제입니다.

$ftp_server = "ftp.example.com";
$ftp_username = "username";
$ftp_password = "password";
$local_file = "local_file.txt";
$server_file = "/remote_file.txt";

// cURL 초기화
$ch = curl_init();

// FTP 설정
curl_setopt($ch, CURLOPT_URL, "ftp://$ftp_username:$ftp_password@$ftp_server/$server_file");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, fopen($local_file, 'w'));

// 파일 다운로드
if (curl_exec($ch)) {
    echo "파일이 성공적으로 다운로드되었습니다.";
} else {
    echo "파일 다운로드에 실패했습니다.";
}

// cURL 종료
curl_close($ch);


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.