Uploading files to FTP server from PHP Script

For one of my project I was required to upload files on an FTP server from the PHP script. Searching on Google I found code required but it was not completely available at one place. So I thought to share this here for use by others as tried and tested code, working on a live website.

This script was created for moving the just uploaded file to FTP server. That is why it uses $_FILES[“tmp_name”] as local file. You can change to your file location, if it is already uploaded.

 

Please replace the variables in first four lines according to the settings you have for your target FTP server.


$ftp_server = "ftp.yourserver.com";
$ftp_user_name = "ftpuser";
$ftp_user_pass = "ftppassword";
$remote_dir = "/target/folder/on/ftp/server";

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = @ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

//default values
$file_url = "";

if($login_result) {
//set passive mode enabled
ftp_pasv($conn_id, true);

//check if directory exists and if not then create it
if(!@ftp_chdir($conn_id, $remote_dir)) {
//create diectory
ftp_mkdir($conn_id, $remote_dir);
//change directory
ftp_chdir($conn_id, $remote_dir);
}

$file = $_FILES["file"]["tmp_name"];
$remote_file = $_FILES["file"]["name"];

$ret = ftp_nb_put($conn_id, $remote_file, $file, FTP_BINARY, FTP_AUTORESUME);
while(FTP_MOREDATA == $ret) {
$ret = ftp_nb_continue($conn_id);
}

if($ret == FTP_FINISHED) {
echo "File '" . $remote_file . "' uploaded successfully.";
} else {
echo "Failed uploading file '" . $remote_file . "'.";
}
} else {
echo "Cannot connect to FTP server at " . $ftp_server;
}

Scroll to top