Quick answer: connect to FTP from PHP with ftp_connect() and ftp_login(), or better, ftp_ssl_connect() for an encrypted FTPS connection. Turn on passive mode with ftp_pasv() or most transfers will hang. For SFTP, use the phpseclib library.
I wrote this in 2010 for an automated backup script. Plain FTP sends your password unencrypted, so here’s the updated, safer version.
Upload a file over FTPS
<?php
$host = 'ftp.example.com';
$user = 'username';
$pass = getenv( 'FTP_PASS' );
$conn = ftp_ssl_connect( $host, 21, 30 );
if ( ! $conn || ! ftp_login( $conn, $user, $pass ) ) {
exit( 'Could not connect or log in.' );
}
ftp_pasv( $conn, true ); // passive mode: needed behind most firewalls
if ( ftp_put( $conn, '/public_html/backup.zip', __DIR__ . '/backup.zip', FTP_BINARY ) ) {
echo 'Uploaded.';
} else {
echo 'Upload failed.';
}
ftp_close( $conn );
Other useful functions
ftp_get()downloads a file.ftp_nlist()lists a folder.ftp_mkdir()andftp_delete()create folders and delete files.
SFTP with phpseclib
Many servers only allow SFTP (over SSH). PHP’s FTP functions can’t do that, but phpseclib can:
composer require phpseclib/phpseclib:~3.0
use phpseclib3\Net\SFTP;
$sftp = new SFTP( 'example.com' );
if ( ! $sftp->login( 'username', getenv( 'SFTP_PASS' ) ) ) {
exit( 'Login failed' );
}
$sftp->put( '/home/user/backup.zip', __DIR__ . '/backup.zip', SFTP::SOURCE_LOCAL_FILE );
Common problems
- Connects but ftp_put() hangs or times out: passive mode is off.
- Call to undefined function ftp_connect(): the PHP FTP extension isn’t installed. Enable it in your hosting panel.
- Corrupted files: use
FTP_BINARY, notFTP_ASCII, for anything other than plain text.
FAQ
Where should I store the password?
In an environment variable or a config file outside the web root, never in the script itself.
Updated December 2026. Need a WordPress or PHP problem sorted? See my WordPress development services or contact me.