note 47920 deleted from function.ftp-nb-fput by googleguy

From: Date: Tue, 22 Oct 2013 10:13:06 +0000
Subject: note 47920 deleted from function.ftp-nb-fput by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-196902@lists.php.net to get a copy of this message
Note Submitter: pain at ziodex dot com ---- 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 // This will not work // ... $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) { // Establish a new connection to FTP server if(!isset($conn_id2)) { $conn_id2 = ftp_connect($ftp_server); $login_result2 = ftp_login($conn_id2, $ftp_user_name, $ftp_user_pass); } // Retreive size of uploaded file. if(isset($conn_id2)) { clearstatcache(); // <- this must be included!! $remote_file_size = ftp_size($conn_id2, $remote_file); } // Calculate upload progress $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); ?>

« previous php.notes (#196902) next »