How to upload files via FTP using PHP ?


In this tutorial, we are going to learn to upload files via FTP using PHP.

The File Transfer Protocol (FTP) is a standard communication protocol used for the transfer of computer files from a server to a client on a computer network. FTP is built on a client–server model architecture using separate control and data connections between the client and the server.

We will be using an in build PHP function : ftp_connect

ftp_connect(string $hostname, int $port = 21, int $timeout = 90): FTP\Connection|false

ftp_connect() opens an FTP connection to the specified hostname.


hostname : The FTP server address. This parameter shouldn’t have any trailing slashes and shouldn’t be prefixed with ftp://

port : This parameter specifies an alternate port to connect to. If it is omitted or set to zero, then the default FTP port, 21, will be used.

timeout : This parameter specifies the timeout in seconds for all subsequent network operations. If omitted, the default value is 90 seconds.

Full Source Code to Upload File via FTP using PHP

function uploadFTP($server, $username, $password, $local_file, $remote_dir, $filename){
    // connect to server
    $connection = ftp_connect($server) or die("Couldn't connect to $server"); 

    // login
    if (@ftp_login($connection, $username, $password)){
        // successfully connected
        echo 'connection failed';
        return false;
    ftp_pasv($connection, true);
    ftp_put($connection, $remote_dir.$filename, $local_file, FTP_BINARY);
    echo 'upload success';
    return true;

$server = '*****'; //FTP Host
$user = '*****'; //FTP Username
$password = '*****'; //FTP Password
$local_file = "*****"; //Path to Local File (example : C:/xampp/htdocs/ftp/image.jpeg)
$remote_dir = '*****'; //Path from FTP root to upload folder (example : /myFolder/subFolder/)
$filename_after_upload = '****'; //filename that will be given to uploaded file (example : abc.jpg)

uploadFTP($server, $user, $password, $local_file, $remote_dir, $filename_after_upload);


ALSO READ  Build your own Google Analytics easily using PHP

Comments are closed.