How to download a file with ftp in php?

by raphael_tillman , in category: PHP General , 5 months ago

How to download a file with ftp in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 5 months ago

@raphael_tillman 

To download a file using FTP in PHP, you can make use of the ftp_get() function. Here's an example that demonstrates the process:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// FTP server details
$ftpServer = 'example.com';
$ftpUsername = 'username';
$ftpPassword = 'password';

// Remote file path on the FTP server
$remoteFilePath = '/path/to/file.txt';

// Local file path where the downloaded file should be saved
$localFilePath = 'local_file.txt';

// Connect to FTP server
$ftpConnection = ftp_connect($ftpServer);
ftp_login($ftpConnection, $ftpUsername, $ftpPassword);

// Download the file
if (ftp_get($ftpConnection, $localFilePath, $remoteFilePath, FTP_BINARY)) {
    echo "File downloaded successfully.";
} else {
    echo "Failed to download the file.";
}

// Close the FTP connection
ftp_close($ftpConnection);


Make sure to replace the example.com, username, password, /path/to/file.txt, and local_file.txt with your specific details.


This code establishes a connection to the FTP server and logs in using the provided credentials. Then, it uses the ftp_get() function to download the file specified by $remoteFilePath to the local file specified by $localFilePath. The FTP_BINARY constant is used to ensure that the file is transferred in binary mode.


Finally, the FTP connection is closed. The code also includes error handling to check if the file download was successful or not.