In web development, working with an FTP server through PHP is a common task. This article will guide you on how to connect to an FTP server using PHP, search for files in a specific directory, and download files. Whether you need to automate file transfers or directly retrieve files from an FTP server, this guide will provide clear instructions.
First, we need to use PHP's ftp_connect() function to connect to the FTP server. Here's the basic syntax:
$conn = ftp_connect($ftp_server, $ftp_port, $timeout);
In this example, $ftp_server refers to the FTP server address, $ftp_port is the server port (default is 21), and $timeout represents the connection timeout.
After establishing the connection, we need to log in using the ftp_login() function. Here’s how to use it:
$login_result = ftp_login($conn, $ftp_username, $ftp_password);
In this case, $conn is the FTP connection handle, and $ftp_username and $ftp_password are the login credentials for the FTP server.
After a successful login, we can use the ftp_nlist() function to get a list of files and directories in a specific FTP directory. Here's how to use it:
$file_list = ftp_nlist($conn, $remote_directory);
In this example, $remote_directory is the path of the directory you want to search, and $file_list will return an array containing all the files and directories in that directory.
If you want to download files from the FTP server, you can use the ftp_get() function. Here is an example:
$download_result = ftp_get($conn, $local_file_path, $remote_file_path, FTP_BINARY);
In this case, $local_file_path is the local path where the file will be saved, $remote_file_path is the path to the file on the FTP server, and FTP_BINARY specifies the transfer mode.
$local_file_path = 'C:/Downloads/file.txt'; $remote_file_path = '/path/to/file.txt'; $download_result = ftp_get($conn, $local_file_path, $remote_file_path, FTP_BINARY); if ($download_result) { echo 'File downloaded successfully'; } else { echo 'File download failed'; }
By following the steps above, you can use PHP to connect to an FTP server, search for files, and download them. First, connect to the FTP server with ftp_connect(), log in using ftp_login(), then retrieve the file list with ftp_nlist() and finally download files with ftp_get().
It is important to ensure that your PHP environment has the FTP extension enabled, and that the FTP server has the appropriate permissions set. If you encounter similar needs during development, this guide will help you quickly implement the required functionality.