PHP FTP functions allow you to connect to remote FTP servers and manage files directly from your PHP scripts. You can upload, download, delete, or list files using built-in functions like ftp_connect()
, ftp_login()
, ftp_put()
, and more. These functions are useful for automating file transfers or managing remote servers. FTP must be enabled in your php.ini
. Always close the connection using ftp_close()
after operations.
📄 File Name: ftp-example.php
1. Connect to FTP Server
<?php
$ftp_server = "ftp.example.com";
$ftp_user = "username";
$ftp_pass = "password";
// Establish connection
$conn = ftp_connect($ftp_server);
// Login
if (@ftp_login($conn, $ftp_user, $ftp_pass)) {
echo "Connected to FTP server!";
} else {
echo "FTP login failed!";
}
?>
2. Upload a File
$local_file = "local.txt";
$remote_file = "server.txt";
if (ftp_put($conn, $remote_file, $local_file, FTP_ASCII)) {
echo "File uploaded successfully.";
} else {
echo "Upload failed.";
}
3. Download a File
$local_file = "downloaded.txt";
$remote_file = "server.txt";
if (ftp_get($conn, $local_file, $remote_file, FTP_ASCII)) {
echo "File downloaded successfully.";
} else {
echo "Download failed.";
}
4. List Files in Directory
$files = ftp_nlist($conn, ".");
print_r($files);
5. Delete a File
if (ftp_delete($conn, "old_file.txt")) {
echo "File deleted.";
} else {
echo "Delete failed.";
}
6. Close Connection
ftp_close($conn);
Summary Table
Task | Function |
---|---|
Connect to FTP | ftp_connect() |
Login | ftp_login() |
Upload file | ftp_put() |
Download file | ftp_get() |
List files | ftp_nlist() |
Delete file | ftp_delete() |
Close connection | ftp_close() |
⚠️ Requirements
- FTP extension must be enabled in your
php.ini
(extension=ftp
) - FTP server must be reachable from your PHP host