While trying to create a progress bar for uploading files with the ftp_nb_fput() function
I've noticed that the ftp_size() function will not work during the upload progess if you are using the
same resource handle.
<?php
$ret = ftp_nb_fput($conn_id, $remote_file, $fp, FTP_BINARY);
while ($ret == FTP_MOREDATA) {
$remote_file_size = ftp_size($conn_id, $remote_file);
$ret = ftp_nb_continue($conn_id);
}
?>
However, by creating a new connection to the server you can retrieve current file size of the uploaded file, then
compare it with your local file to calculate the progress. A full example follows:
<?php
ob_end_flush();
$remote_file = 'remote.txt';
$local_file = 'local.txt';
$fp = fopen($local_file, 'r');
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
$ret = ftp_nb_fput($conn_id, $remote_file, $fp, FTP_BINARY);
while ($ret == FTP_MOREDATA) {
if(!isset($conn_id2)) {
$conn_id2 = ftp_connect($ftp_server);
$login_result2 = ftp_login($conn_id2, $ftp_user_name, $ftp_user_pass);
}
if(isset($conn_id2)) {
clearstatcache(); $remote_file_size = ftp_size($conn_id2, $remote_file);
}
$local_file_size = filesize($local_file);
if (isset($remote_file_size) && $remote_file_size > 0 ){
$i = ($remote_file_size/$local_file_size)*100;
printf("%d%% uploaded<br>", $i);
flush();
}
$ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED) {
print("There was an error uploading the file...<br>");
exit(1);
}
else {
print("Done.<br>");
}
fclose($fp);
?>