How I Connect to FTP/SFTP and upload files using PHP

Arfan
2 min readMar 15, 2022

--

Here is I will explain how to use FTP and SFTP for file upload using php. We need Host, Port, Username and Password. Here is the full code example if connection and uploading files.

Using FTP

$ftp_host = "example.com";
$ftp_port = "21";
$ftp_username = "username";
$ftp_password = "********";
$conn_id = ftp_connect($ftp_host); /// contact to host
if(!conn_id) return "something wrong";
if (@ftp_login($conn_id, $ftp_username, $ftp_password)) {
ftp_putAll($conn_id, $src_file , $dest_path);
}
function ftp_putAll($conn_id, $src_dir, $dst_dir) {
$d = dir($src_dir);
while($file = $d->read()) { // do this for each file
if ($file != "." && $file != "..") { // to prevent an infinite loop
if (is_dir($src_dir."/".$file)) { // do the following if it is a directory
if (!@ftp_chdir($conn_id, $dst_dir."/".$file)) {
ftp_mkdir($conn_id, $dst_dir."/".$file); // create directories that do not yet exist
}
ftp_putAll($conn_id, $src_dir."/".$file, $dst_dir."/".$file); // recursive part
} else {
$upload = ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY); // put the files
}
}
}
$d->close();
}

Using SFTP

$ftp_host = "example.com";
$ftp_port = "21";
$ftp_username = "username";
$ftp_password = "********";
$conn_id = ftp_connect($ftp_host); /// contact to host
if(!conn_id) return "something wrong";
$sftp = new \phpseclib\Net\SFTP($ftp_host, $ftp_port);
if (!$sftp->login($ftp_username, $ftp_password))
return "Something Wrong";
sftp_putAll($sftp, $src_dir, $dest_path);function sftp_putAll($sftp, $src_dir, $dst_dir) {
$d = dir($src_dir);
while($file = $d->read()) {
if ($file != "." && $file != "..") {
if (is_dir($src_dir."/".$file)) {
if (!$sftp->chdir($dst_dir."/".$file)) {
$sftp->mkdir($dst_dir."/".$file);
}
sftp_putAll($sftp, $src_dir."/".$file, $dst_dir."/".$file);
} else {
$file_content = file_get_contents($src_dir."/".$file);
$sftp->put($dst_dir."/".$file, $file_content);
}
}
}
$d->close();
}

That’s all for now.

--

--