function poll() { if (!count($this->connections)) { return -1; } // no connections open $return = 0; // we have transfers in queue if (count($this->transfers)) { foreach ($this->transfers as $k => $transfer) { // if we have an open connection if ($ftph = $this->get_free_connection()) { $this->activate_transfer($ftph, $k); } else { // none available so stop sifting through the queue break; } } $return = 1; // we are busy } foreach ($this->active_connections as $k => $transfer) { $ftph = $transfer['ftph']; if ($transfer['type'] == 'put') { if (!$transfer['status']) { $ret = ftp_nb_put($ftph, $transfer['remote'], $transfer['local'], FTP_BINARY); if ($ret == FTP_FAILED && $transfer['error_callback']) { $transfer['error_callback']($transfer, $this); } else { if ($ret == FTP_MOREDATA) { $this->active_connections[$k]['status'] = 'busy'; } else { if ($ret == FTP_FINISHED && $transfer['success_callback']) { $transfer['success_callback']($transfer, $this); } } } if ($ret == FTP_FAILED || $ret == FTP_FINISHED) { $this->free_connection($ftph); } } elseif ($transfer['status'] == 'busy') { $ret = ftp_nb_continue($ftph); if ($ret == FTP_FAILED && $transfer['error_callback']) { $transfer['error_callback']($transfer, $this); } else { if ($ret == FTP_FINISHED && $transfer['success_callback']) { $transfer['success_callback']($transfer, $this); } } if ($ret == FTP_FAILED || $ret == FTP_FINISHED) { $this->free_connection($ftph); } } } $return = 1; // we are busy } return $return; // we are done }
function syncFolderToFtp($host, $username, $password, $remote_backup, $backup_folder) { $ftp = ftp_connect($host); // connect to the ftp server ftp_login($ftp, $username, $password); // login to the ftp server ftp_chdir($ftp, $remote_backup); // cd into the remote backup folder // copy files from folder to remote folder $files = glob($backup_folder . '*'); $c = 0; $allc = count($files); foreach ($files as $file) { $c++; $file_name = basename($file); echo "\n {$c}/{$allc}: {$file_name}"; $upload = ftp_nb_put($ftp, $file_name, $file, FTP_BINARY); // non-blocking put, uploads the local backup onto the remote server while ($upload == FTP_MOREDATA) { // Continue uploading... $upload = ftp_nb_continue($ftp); } if ($upload != FTP_FINISHED) { echo " ... ERROR"; } else { echo " ... OK"; } } ftp_close($ftp); // closes the connection }
/** * 上传文件 * */ public function upload($remotefile, $localfile) { $res = ftp_nb_put($this->ftpobj, $remotefile, $localfile, $this->mode, ftp_size($this->ftpobj, $remotefile)); while ($res == FTP_MOREDATA) { $res = ftp_nb_continue($this->ftpobj); } if ($res != FTP_FINISHED) { return FALSE; } return TRUE; }
function put($localFile, $remoteFile = '') { if ($remoteFile == '') { $remoteFile = end(explode('/', $localFile)); } $res = ftp_nb_put($this->ftpR, $remoteFile, $localFile, FTP_BINARY); while ($res == FTP_MOREDATA) { $res = ftp_nb_continue($this->ftpR); } if ($res == FTP_FINISHED) { return true; } elseif ($res == FTP_FAILED) { return false; } }
/** * FTP-文件上传 * @param string $localFile 本地文件 * @param string $ftpFile Ftp文件 * @return bool */ public function upload($localFile, $ftpFile) { if (!$localFile || !$ftpFile) { return false; } $ftppath = dirname($ftpFile); if (!empty($ftppath)) { //创建目录 $this->makeDir($ftppath); @ftp_chdir($this->link, $ftppath); $ftpFile = basename($ftpFile); } $ret = ftp_nb_put($this->link, $ftpFile, $localFile, FTP_BINARY); while ($ret == FTP_MOREDATA) { $ret = ftp_nb_continue($this->link); } return $ret == FTP_FINISHED; }
/** * FTP-文件上传 * * @access public * * @param string $localFile 本地文件 * @param string $ftpFile Ftp文件 * * @return boolean */ public function upload($localFile, $ftpFile) { if (!$localFile || !$ftpFile) { return false; } $ftpPath = dirname($ftpFile); if ($ftpPath) { //创建目录 $this->makeDir($ftpPath); @ftp_chdir($this->_linkId, $ftpPath); $ftpFile = basename($ftpFile); } $ret = ftp_nb_put($this->_linkId, $ftpFile, $localFile, FTP_BINARY); while ($ret == FTP_MOREDATA) { $ret = ftp_nb_continue($this->_linkId); } if ($ret != FTP_FINISHED) { return false; } return true; }
/** * FTP-文件上传 * * @param string $local_file 本地文件 * @param string $ftp_file Ftp文件 * * @return bool */ public function upload($local_file, $ftp_file) { if (empty($local_file) || empty($ftp_file)) { return false; } $ftppath = dirname($ftp_file); if (!empty($ftppath)) { //创建目录 $this->makeDir($ftppath); @ftp_chdir($this->linkid, $ftppath); $ftp_file = basename($ftp_file); } $ret = ftp_nb_put($this->linkid, $ftp_file, $local_file, FTP_BINARY); while ($ret == FTP_MOREDATA) { $ret = ftp_nb_continue($this->linkid); } if ($ret != FTP_FINISHED) { return false; } return true; }
function start_connect($files) { global $task, $_CONFIG; if ($_REQUEST[task] == 'move' || $_REQUEST[task2] == 'move') { } else { $source_file[0] = "restore/XCloner.php"; $destination_file[0] = $_REQUEST[ftp_dir] . "/XCloner.php"; $source_file[1] = "restore/TAR.php"; $destination_file[1] = $_REQUEST[ftp_dir] . "/TAR.php"; } foreach ($files as $file) { $source_file[] = $_CONFIG['clonerPath'] . "/" . $file; $destination_file[] = $_REQUEST[ftp_dir] . "/" . $file; } list($fhost, $fport) = explode(":", $_REQUEST[ftp_server]); if ($fport == "") { $fport = '21'; } $ftp_timeout = '3600'; // set up basic connection if (!$_CONFIG[secure_ftp]) { $conn_id = ftp_connect($fhost, (int) $fport, (int) $ftp_timeout); $connect = "Normal"; } else { $conn_id = ftp_ssl_connect($fhost, (int) $fport, (int) $ftp_timeout); $connect = "Secure"; } // login with username and password $login_result = @ftp_login($conn_id, $_REQUEST[ftp_user], $_REQUEST[ftp_pass]); // check connection if (!$conn_id || !$login_result) { echo "<b style='color:red'>" . LM_MSG_BACK_2 . "</b>"; echo "<b style='color:red'>Attempted to connect to " . $_REQUEST[ftp_server] . " for user " . $_REQUEST[ftp_user] . "</b>"; return; } else { #echo "Connected to $_REQUEST[ftp_server], for user $_REQUEST[ftp_user]"; } if ($_CONFIG[system_ftptransfer] == 1) { // turn passive mode on @ftp_pasv($conn_id, true); $mode = "Passive"; } else { // turn passive mode off @ftp_pasv($conn_id, false); $mode = "Active"; } echo "Connected to {$connect} ftp server <b>{$_REQUEST['ftp_server']} - {$mode} Mode</b><br />"; for ($i = 0; $i < sizeof($source_file); $i++) { echo "<br />Moving source file <b>" . $source_file[$i] . "</b>"; // upload the file if (!$_REQUEST['ftp_inct']) { $ret = ftp_put($conn_id, $destination_file[$i], $source_file[$i], FTP_BINARY); if ($ret) { echo "<br /><b>Upload success to <i>{$destination_file[$i]}</i> ...<br /></b>"; } else { echo "<b style='color:red'>FTP upload has failed for file {$destination_file[$i]} ! Stopping ....<br /></b>"; return; } } if ($_REQUEST['ftp_inct']) { $size = filesize($source_file[$i]); $dsize = ftp_size($conn_id, $destination_file[$i]); $perc = sprintf("%.2f", $dsize * 100 / $size); echo " - uploaded {$perc}% from {$size} bytes <br>"; $ret = ftp_nb_put($conn_id, $destination_file[$i], $source_file[$i], FTP_BINARY, FTP_AUTORESUME); // check upload status if ($ret == FTP_FAILED) { echo "<b style='color:red'>FTP upload has failed for file {$destination_file[$i]} ! Stopping ....<br /></b>"; return; } else { $j = 1; while ($ret == FTP_MOREDATA) { // Do whatever you want #echo ". "; // Continue uploading... $ret = ftp_nb_continue($conn_id); if ($j++ % 500 == 0) { @ftp_close($conn_id); echo "<script>\n\t\tvar sURL = unescape('" . $_SERVER[REQUEST_URI] . "');\n\n\t function refresh()\n\t {\n\t // This version of the refresh function will cause a new\n\t // entry in the visitor's history. It is provided for\n\t // those browsers that only support JavaScript 1.0.\n\t //\n\t window.location.href = sURL;\n\t }\n\n\t\tsetTimeout( \"refresh()\", 2*1000 );\n\t\t\n\t\t</script>"; return 1; break; } } if ($ret == FTP_FINISHED) { echo "<b>Upload success to <i>{$destination_file[$i]}</i> ...<br /></b>"; } } } } // close the FTP stream @ftp_close($conn_id); $redurl = $_REQUEST[ftp_url] . "/XCloner.php"; if (substr($redurl, 0, 7) != "http://" && substr($redurl, 0, 8) != "https://") { $redurl = "http://" . trim($redurl); } if ($_REQUEST['ftp_inct']) { if ($_REQUEST['refresh_done'] != 1) { echo "<script>\n\t\tvar sURL = unescape('" . $_SERVER[REQUEST_URI] . "&refresh_done=1');\n\n\t function refresh()\n\t {\n\t // This version of the refresh function will cause a new\n\t // entry in the visitor's history. It is provided for\n\t // those browsers that only support JavaScript 1.0.\n\t //\n\t window.location.href = sURL;\n\t }\n\n\t\tsetTimeout( \"refresh()\", 2*1000 );\n\t\t\n\t\t</script>"; return 1; } } else { $_REQUEST['refresh_done'] = 1; } if ($_REQUEST['refresh_done'] == 1) { if ($_REQUEST[task] == 'move' || $_REQUEST[task2] == 'move') { echo "<br><br><h2>" . LM_MSG_BACK_3 . "</h2>"; return 1; } else { echo "<br><br><h2>" . LM_MSG_BACK_4 . " <br /><a href='" . $redurl . "'>click here to continue...</a></h2>"; return 1; } } return 0; }
/** * Stores a file on the server (non blocking) * @link http://php.net/ftp_nb_put * * @param string $remoteFile The remote file path * @param string $localFile The local file path * @param integer $mode The transfer mode (FTPWrapper::ASCII or FTPWrapper::BINARY) * @param integer $startpos The position in the remote file to start downloading from * @return integer FTPWrapper::FAILED, FTPWrapper::FINISHED or FTPWrapper::MOREDATA */ public function putNb($remoteFile, $localFile, $mode = self::BINARY, $startpos = 0) { return ftp_nb_put($this->connection->getStream(), $remoteFile, $localFile, $mode, $startpos); }
function ftp_uploading_compile($ftpFolder, $connect_data, $current_file_uri, $current_file_dir) { $ftp_connect = @ftp_connect($connect_data['ftp_hostname']); $ftp_login = @ftp_login($ftp_connect, $connect_data['ftp_username'], $connect_data['ftp_password']); if (!$ftp_login) { return false; } else { if (substr($ftpFolder, strlen($ftpFolder) - 1) != "/") { $d = ftp_nb_put($ftp_connect, $ftpFolder . '/archive.zip', $current_file_dir, FTP_BINARY); } else { $d = ftp_nb_put($ftp_connect, $ftpFolder . 'archive.zip', $current_file_dir, FTP_BINARY); } while ($d == FTP_MOREDATA) { $d = ftp_nb_continue($ftp_connect); } if ($d != FTP_FINISHED) { exit(1); } if (substr($ftpFolder, strlen($ftpFolder) - 1) != "/") { $d = ftp_nb_put($ftp_connect, $ftpFolder . '/unziper.php', COMPILER_FOLDER . 'unzip.php', FTP_BINARY); } else { $d = ftp_nb_put($ftp_connect, $ftpFolder . 'unziper.php', COMPILER_FOLDER . 'unzip.php', FTP_BINARY); } while ($d == FTP_MOREDATA) { $d = ftp_nb_continue($ftp_connect); } if ($d != FTP_FINISHED) { exit(1); } if (substr($connect_data['site_url'], strlen($connect_data['site_url']) - 1) != "/") { $host['unzip'] = $connect_data['site_url'] . '/unziper.php'; $host['dump'] = $connect_data['site_url'] . '/db_upload.php'; } else { $host['unzip'] = $connect_data['site_url'] . 'unziper.php'; $host['dump'] = $connect_data['site_url'] . 'db_upload.php'; } $host['link'] = $connect_data['site_url']; // close connection ftp_close($ftp_connect); echo json_encode($host); return true; } }
/** * This function will upload a file to the ftp-server. You can either specify a * absolute path to the remote-file (beginning with "/") or a relative one, * which will be completed with the actual directory you selected on the server. * You can specify the path from which the file will be uploaded on the local * maschine, if the file should be overwritten if it exists (optionally, default * is no overwriting) and in which mode (FTP_ASCII or FTP_BINARY) the file * should be downloaded (if you do not specify this, the method tries to * determine it automatically from the mode-directory or uses the default-mode, * set by you). * If you give a relative path to the local-file, the script-path is used as * basepath. * * @param string $local_file The local file to upload * @param string $remote_file The absolute or relative path to the file to * upload to * @param bool $overwrite (optional) Whether to overwrite existing file * @param int $mode (optional) Either FTP_ASCII or FTP_BINARY * @param int $options (optional) Flags describing the behaviour of this * function. Currently NET_FTP_BLOCKING and * NET_FTP_NONBLOCKING are supported, of which * NET_FTP_NONBLOCKING is the default. * * @access public * @return mixed True on success, otherwise PEAR::Error * @see NET_FTP_ERR_LOCALFILENOTEXIST, * NET_FTP_ERR_OVERWRITEREMOTEFILE_FORBIDDEN, * NET_FTP_ERR_UPLOADFILE_FAILED, NET_FTP_NONBLOCKING, NET_FTP_BLOCKING */ function put($local_file, $remote_file, $overwrite = false, $mode = null, $options = 0) { if ($options & (NET_FTP_BLOCKING | NET_FTP_NONBLOCKING) === (NET_FTP_BLOCKING | NET_FTP_NONBLOCKING)) { return $this->raiseError('Bad options given: NET_FTP_NONBLOCKING and ' . 'NET_FTP_BLOCKING can\'t both be set', NET_FTP_ERR_BADOPTIONS); } $usenb = !($options & NET_FTP_BLOCKING == NET_FTP_BLOCKING); if (!isset($mode)) { $mode = $this->checkFileExtension($local_file); } $remote_file = $this->_constructPath($remote_file); if (!@file_exists($local_file)) { return $this->raiseError("Local file '{$local_file}' does not exist.", NET_FTP_ERR_LOCALFILENOTEXIST); } if (@ftp_size($this->_handle, $remote_file) != -1 && !$overwrite) { return $this->raiseError("Remote file '" . $remote_file . "' exists and may not be overwriten.", NET_FTP_ERR_OVERWRITEREMOTEFILE_FORBIDDEN); } if (function_exists('ftp_alloc')) { ftp_alloc($this->_handle, filesize($local_file)); } if ($usenb && function_exists('ftp_nb_put')) { $res = @ftp_nb_put($this->_handle, $remote_file, $local_file, $mode); while ($res == FTP_MOREDATA) { $this->_announce('nb_put'); $res = @ftp_nb_continue($this->_handle); } } else { $res = @ftp_put($this->_handle, $remote_file, $local_file, $mode); } if (!$res) { return $this->raiseError("File '{$local_file}' could not be uploaded to '" . $remote_file . "'.", NET_FTP_ERR_UPLOADFILE_FAILED); } else { return true; } }
/** * Upload a file to the FTP server. * * @param string local file * @param string remote file * @param const mode * @return boolean */ public function put($local, $remote = null, $mode = FTP_BINARY, $asynchronous = false) { if ($this->getActive()) { if (!isset($remote) || $remote == null || !is_string($remote) || trim($remote) == '') { $remote = basename($local); try { $remote = $this->currentDir() . '/' . $remote; } catch (\Exception $e) { } } if ($asynchronous === false) { // Upload the local file to the remote location specified if (ftp_put($this->_connection, $remote, $local, $mode)) { return true; } else { return false; } } else { $ret = ftp_nb_put($this->_connection, $remote, $local, $mode); while ($ret == FTP_MOREDATA) { $ret = ftp_nb_continue($this->_connection); } if ($ret !== FTP_FINISHED) { return false; } else { return true; } } } else { throw new \Exception('EFtpComponent is inactive and cannot perform any FTP operations.'); } }
/** * Uploads the files asynchronously, so the class can perform other operations * while files are being uploaded, such : * display a progress bar in indeterminate mode. * * @param string $dest Changes from current to the specified directory. * @param boolean $overwrite (optional) overwrite existing files. * * @return mixed a null array if all files transfered * @since 1.1 * @access public * @see FTP_Upload::setFiles() */ function moveTo($dest, $overwrite = false) { if (!is_string($dest)) { Error_Raise::raise($this->_package, HTML_PROGRESS_ERROR_INVALID_INPUT, 'exception', array('var' => '$dest', 'was' => gettype($dest), 'expected' => 'string', 'paramnum' => 1), PEAR_ERROR_TRIGGER); } elseif (!is_bool($overwrite)) { Error_Raise::raise($this->_package, HTML_PROGRESS_ERROR_INVALID_INPUT, 'exception', array('var' => '$overwrite', 'was' => gettype($overwrite), 'expected' => 'boolean', 'paramnum' => 2), PEAR_ERROR_TRIGGER); } $dir = parent::_changeDir($dest); if (PEAR::isError($dir)) { return $dir; } $remoteFiles = ftp_nlist($this->_conn, '.'); if ($remoteFiles === false) { return PEAR::raiseError('Couldn\'t read directory ' . $dest); } $nomove = array(); // files not transfered on remote host foreach ($this->_files as $file) { if (!$overwrite && in_array(basename($file), $remoteFiles)) { // file already exists, skip to next one continue; } // writes file caption $status = ob_get_clean(); $status = '<script type="text/javascript">self.setStatus(\''; $status .= sprintf($this->captionMask, basename($file)); $status .= '\'); </script>'; echo $status; ob_start(); $ret = ftp_nb_put($this->_conn, basename($file), $file, FTP_BINARY); while ($ret == FTP_MOREDATA) { $this->_progress->display(); // sleep a bit ... for ($i = 0; $i < $this->_progress->_anim_speed * 1000; $i++) { } if ($this->_progress->getPercentComplete() == 1) { $this->_progress->setValue(0); } else { $this->_progress->incValue(); } // upload Continue ... $ret = ftp_nb_continue($this->_conn); } if ($ret != FTP_FINISHED) { $nomove[] = $file; } } return $nomove; }
/** * @see RemoteDriver::put($mode, $local_file, $remote_file, $asynchronous) */ public function put($local_file, $remote_file = null, $mode = FTP_ASCII, $asynchronous = false) { $this->connectIfNeeded(); if (!isset($remote_file) || $remote_file == null || !is_string($remote_file) || trim($remote_file) == "") { $remote_file = basename($local_file); } $this->param = array('remote_file' => $remote_file, 'local_file' => $local_file, 'asynchronous' => $asynchronous); if ($asynchronous !== true) { if (!ftp_put($this->handle, $remote_file, $local_file, $mode)) { throw new FtpException(Yii::t('gftp', 'Could not put file "{local_file}" on "{remote_file}" on server "{host}"', ['host' => $this->host, 'remote_file' => $remote_file, 'local_file' => $local_file])); } } else { $ret = ftp_nb_put($this->handle, $remote_file, $local_file, $mode); while ($ret == FTP_MOREDATA) { $ret = ftp_nb_continue($this->handle); } if ($ret !== FTP_FINISHED) { throw new FtpException(Yii::t('gftp', 'Could not put file "{local_file}" on "{remote_file}" on server "{host}"', ['host' => $this->host, 'remote_file' => $full_remote_file, 'local_file' => $local_file])); } } return $full_remote_file; }
public function put($path, $local) { $path = $this->path($path); // Directory support if (is_dir($local)) { throw new Engine_Vfs_Adapter_Exception(sprintf('Unable to put "%s" to "%s": directories not supported', $path, $local)); } // Make sure parent exists if (!$this->exists(dirname($path))) { $this->makeDirectory(dirname($path), true); } // Get mode $mode = $this->getFileMode($path); // Non-blocking mode if (@function_exists('ftp_nb_put')) { $resource = $this->getResource(); $res = @ftp_nb_put($resource, $path, $local, $mode); while ($res == FTP_MOREDATA) { //$this->_announce('nb_put'); $res = @ftp_nb_continue($resource); } $return = $res === FTP_FINISHED; } else { $return = @ftp_put($this->_handle, $path, $local, $mode); } // Set umask permission try { $this->mode($path, $this->getUmask(0666)); } catch (Exception $e) { // Silence } if (!$return) { throw new Engine_Vfs_Adapter_Exception(sprintf('Unable to put "%s" to "%s"', $path, $local)); } return true; }
/** * Upload local file. Create remote directory path if necessary. * Remote file path must start with root directory. * * @throws * @param string $local_file * @param string $remote_file */ public function put($local_file, $remote_file) { if ($this->hasCache($remote_file, File::md5($local_file))) { $this->_log($remote_file . ' exists'); return; } $this->mkdir(dirname($remote_file)); if (!empty($this->conf['use_cache']) && isset($this->cache[$remote_file])) { unset($this->cache[$remote_file]); } $this->_log("upload {$local_file} as {$remote_file}"); $ret = @ftp_nb_put($this->ftp, $remote_file, $local_file, FTP_BINARY); while ($ret === FTP_MOREDATA) { $ret = @ftp_nb_continue($this->ftp); } if ($ret !== FTP_FINISHED) { throw new Exception('put file failed', "local_file={$local_file} remote_file={$remote_file}"); } $this->cache[$remote_file] = [File::md5($local_file), File::size($local_file), File::lastModified($local_file)]; }
/** * Uploads a file from the local system to the FTP server but does not block other operations * * @param string $localfile Local path of the file to upload * @param string $remotefile Remote path where the file should be stored * @param string $mode Transfer mode for the file. (auto or ascii or binary) * @param integer $position Pointer of the local file from where the upload should be resumed * @return integer 0 = Transfer failed (FTP_FAILED) | 1 = Transfer finished (FTP_FINISHED) | 2 = Transfer in progress (FTP_MOREDATA) */ public function uploadUnobtrusive($localfile, $remotefile, $mode = 'auto', $position = null) { if (is_resource($this->cid)) { $transfermode = self::transferMode($mode); return ftp_nb_put($this->cid, $remotefile, $localfile, $transfermode, $position); } }
<?php $ftp = null; var_dump(ftp_connect(array())); var_dump(ftp_connect('127.0.0.1', 0, -3)); var_dump(ftp_raw($ftp)); var_dump(ftp_mkdir($ftp)); var_dump(ftp_rmdir($ftp)); var_dump(ftp_nlist($ftp)); var_dump(ftp_rawlist($ftp)); var_dump(ftp_fget($ftp)); var_dump(ftp_nb_fget($ftp)); var_dump(ftp_nb_get($ftp)); var_dump(ftp_pasv($ftp)); var_dump(ftp_nb_continue()); var_dump(ftp_fput()); var_dump(ftp_nb_fput($ftp)); var_dump(ftp_put($ftp)); var_dump(ftp_nb_put($ftp)); var_dump(ftp_size($ftp)); var_dump(ftp_mdtm($ftp)); var_dump(ftp_rename($ftp)); var_dump(ftp_site($ftp)); var_dump(ftp_set_option($ftp)); var_dump(ftp_get_option($ftp));
function upload($file, $name = "") { if (!$file) { return false; } if (!$name) { $name = basename($file); } $this->cd($this->ftp_dir); if ($name != $file) { $dir_string = substr($file, 0, -strlen($name)); $this->make($dir_string); } //如果文件存在,且大小及修改时间一样时,则跳过上传 if ($this->is_exist($file)) { return true; } if (ftp_size($this->conn, $file) > 0) { ftp_delete($this->conn, $file); } //判断文件是否存在 //尝试异步上传 $ret = ftp_nb_put($this->conn, $file, $file, FTP_BINARY); while ($ret == FTP_MOREDATA) { $ret = ftp_nb_continue($this->conn); } if ($ret != FTP_FINISHED) { return false; } else { return true; } }
function uploadFile($local, $remote) { //get handle to a connection stream $index = $this->getIdleStreamIndex(); $this->localFiles[$index] = $local; //initiate the upload $this->conStats[$index] = ftp_nb_put($this->conIds[$index], $remote, $local, FTP_BINARY); if ($this->conStats[$index] == FTP_FAILED) { //disconnected so try to connect ftp_close($this->conIds[$index]); $this->newStream($index); //try to reupload $this->conStats[$index] = ftp_nb_put($this->conIds[$index], $remote, $local, FTP_BINARY); if ($this->conStats[$index] == FTP_FAILED) { //permament failure die('Connection Error.' . "\r\n"); } } }
/** * 上传文件(支持全新上传和断点续传) * @param string $local 本地文件路径(如e:\abc\def.txt或./a/b/c.txt) * @param string $remote 远程文件全路径(如/a/b/c.txt) * @param boolean $isContinue 是否指定文件断点续传,默认为false,全新上传 * @uses $size = ftp_size($stream, $remote);<br> * <pre> * -1 远程文件不存在<br> * 指定续传:选定了续传、但指定的远程文件不存在。<br> * (开发者可根据此状态来询问客户端是否要继续上传)<br> * (当客户端决定继续上传时,应该采用全新上传方式)<br> * 指定全新上传:正常执行全新上传<br> * 非-1 远程文件已存在<br> * 指定续传:正常执行续传<br> * 指定全新上传:选定了全新上传,但指定的远程文件已存在。<br> * (开发者可根据此状态来询问客户端是否需要覆盖远程文件)<br> * (当客户端决定覆盖上传时,应该先使服务器备份指定的远程文件,再继续全新上传)<br> * </pre> * @return int 上传状态<br> * <pre> * AiFtpStatus::UPLOAD_FILE_SUCCESS为上传成功,<br> * 其它值为上传失败。<br> * 上传失败的原因一般有:连接断开、编码错误、本地文件不存在、远程文件已存在等等<br> * </pre> */ function uploadFile($remote, $local, $isContinue = false) { $remote = $this->upcharconv($remote); $local = $this->scriptToFsCharset($local); if (!file_exists($local)) { return $isContinue ? AiFtpStatus::UPLOAD_HALF_FILE_HASNO_LOCALFILE : AiFtpStatus::UPLOAD_NEW_FILE_HASNO_LOCALFILE; } //返回-1表示远程文件不存在 $size = ftp_size($this->stream, $remote); $ret = null; if (-1 == $size) { if ($isContinue) { return AiFtpStatus::UPLOAD_HALF_FILE_HASNO_REMOTEFILE; } @($ret = ftp_nb_put($this->stream, $remote, $local, FTP_BINARY)); } else { if (!$isContinue) { return AiFtpStatus::UPLOAD_NEW_FILE_EXIST_REMOTEFILE; } @($ret = ftp_nb_put($this->stream, $remote, $local, FTP_BINARY, $size)); } while (FTP_MOREDATA == $ret) { $ret = ftp_nb_continue($this->stream); } if (FTP_FINISHED != $ret) { return $isContinue ? AiFtpStatus::UPLOAD_HALF_FILE_UN_FINISH : AiFtpStatus::UPLOAD_NEW_FILE_UN_FINISH; } return AiFtpStatus::UPLOAD_FILE_SUCCESS; }
private function upload_files() { if ($this->get_files('to_upload')) { set_time_limit(0); $this->log("Connecting to ftp server..."); $conn_id = ftp_connect($this->params['ftp']['hostname'], $this->params['ftp']['port'], 600); if (!$conn_id) { $this->log("There was an error connecting to ftp server\n"); exit; } $this->log("OK\n"); $login_result = ftp_login($conn_id, $this->params['ftp']['username'], $this->params['ftp']['password']); if (!$login_result) { $this->log("Could not authenticate to ftp server\n"); exit; } // turn passive mode on ftp_pasv($conn_id, true); foreach ($this->get_files('to_upload') as $file) { $remote_path = $this->params['ftp']['path'] . '/' . str_replace('[episode]', $file, $this->params['filemask']); $local_path = $this->path('to_upload') . '/' . $file; $this->log("Uploading {$file}..."); $ret = ftp_nb_put($conn_id, $remote_path, $local_path, FTP_BINARY); while ($ret == FTP_MOREDATA) { // Do whatever you want echo "."; // Continue uploading... $ret = ftp_nb_continue($conn_id); } if ($ret != FTP_FINISHED) { echo "There was an error uploading {$file}..."; exit(1); } $this->log("OK\n"); rename($this->path('to_upload') . '/' . $file, $this->path('to_publish') . '/' . $file); } ftp_close($conn_id); } }
/** * This function will upload a file to the ftp-server. You can either specify a absolute * path to the remote-file (beginning with "/") or a relative one, which will be completed * with the actual directory you selected on the server. You can specify * the path from which the file will be uploaded on the local * maschine, if the file should be overwritten if it exists (optionally, default is * no overwriting) and in which mode (FTP_ASCII or FTP_BINARY) the file should be * downloaded (if you do not specify this, the method tries to determine it automatically * from the mode-directory or uses the default-mode, set by you). If you give a relative * path to the local-file, the script-path is used as basepath. * * @access public * @param string $local_file The local file to upload * @param string $remote_file The absolute or relative path to the file to upload to * @param bool $overwrite (optional) Whether to overwrite existing file * @param int $mode (optional) Either FTP_ASCII or FTP_BINARY * @return mixed True on success, otherwise PEAR::Error * @see NET_FTP_ERR_LOCALFILENOTEXIST, NET_FTP_ERR_OVERWRITEREMOTEFILE_FORBIDDEN, NET_FTP_ERR_UPLOADFILE_FAILED */ function put($local_file, $remote_file, $overwrite = false, $mode = null) { if (!isset($mode)) { $mode = $this->checkFileExtension($local_file); } $remote_file = $this->_construct_path($remote_file); if (!@file_exists($local_file)) { return $this->raiseError("Local file '{$local_file}' does not exist.", NET_FTP_ERR_LOCALFILENOTEXIST); } if (@ftp_size($this->_handle, $remote_file) != -1 && !$overwrite) { return $this->raiseError("Remote file '{$remote_file}' exists and may not be overwriten.", NET_FTP_ERR_OVERWRITEREMOTEFILE_FORBIDDEN); } if (function_exists('ftp_nb_put')) { $res = @ftp_nb_put($this->_handle, $remote_file, $local_file, $mode); while ($res == FTP_MOREDATA) { $this->_announce('nb_put'); $res = @ftp_nb_continue($this->_handle); } } else { $res = @ftp_put($this->_handle, $remote_file, $local_file, $mode); } if (!$res) { return $this->raiseError("File '{$local_file}' could not be uploaded to '{$remote_file}'.", NET_FTP_ERR_UPLOADFILE_FAILED); } else { return true; } }
private function handle_file_upload($uploaded_file, $name, $size, $type, $error) { $fileUpload = new stdClass(); $fileUpload->name = basename(stripslashes($name)); $fileUpload->size = intval($size); $fileUpload->type = $type; $fileUpload->error = null; $extension = end(explode(".", $fileUpload->name)); $fileUpload->error = $this->has_error($uploaded_file, $fileUpload, $error); if (!$fileUpload->error) { if (strlen(trim($fileUpload->name)) == 0) { $fileUpload->error = 'Filename not found.'; } } elseif (intval($size) == 0) { $fileUpload->error = 'File received has zero size.'; } elseif (intval($size) > $this->options['max_file_size']) { $fileUpload->error = 'File received is larger than permitted.'; } if (!$fileUpload->error && $fileUpload->name) { if ($fileUpload->name[0] === '.') { $fileUpload->name = substr($fileUpload->name, 1); } $newFilename = MD5(microtime()); // figure out upload type $file_size = 0; // select server from pool $uploadServerId = getAvailableServerId(); $db = Database::getDatabase(true); $uploadServerDetails = $db->getRow('SELECT * FROM file_server WHERE id = ' . $db->quote($uploadServerId)); // override storage path if (strlen($uploadServerDetails['storagePath'])) { $this->options['upload_dir'] = $uploadServerDetails['storagePath']; if (substr($this->options['upload_dir'], strlen($this->options['upload_dir']) - 1, 1) == '/') { $this->options['upload_dir'] = substr($this->options['upload_dir'], 0, strlen($this->options['upload_dir']) - 1); } $this->options['upload_dir'] .= '/'; } // move remotely via ftp if ($uploadServerDetails['serverType'] == 'remote') { // connect ftp $conn_id = ftp_connect($uploadServerDetails['ipAddress'], $uploadServerDetails['ftpPort'], 30); if ($conn_id === false) { $fileUpload->error = 'Could not connect to file server ' . $uploadServerDetails['ipAddress']; } // authenticate if (!$fileUpload->error) { $login_result = ftp_login($conn_id, $uploadServerDetails['ftpUsername'], $uploadServerDetails['ftpPassword']); if ($login_result === false) { $fileUpload->error = 'Could not authenticate with file server ' . $uploadServerDetails['ipAddress']; } } // create the upload folder if (!$fileUpload->error) { $uploadPathDir = $this->options['upload_dir'] . substr($newFilename, 0, 2); if (!ftp_mkdir($conn_id, $uploadPathDir)) { // Error reporting removed for now as it causes issues with existing folders. Need to add a check in before here // to see if the folder exists, then create if not. // $fileUpload->error = 'There was a problem creating the storage folder on '.$uploadServerDetails['ipAddress']; } } // upload via ftp if (!$fileUpload->error) { $file_path = $uploadPathDir . '/' . $newFilename; clearstatcache(); if ($uploaded_file && is_uploaded_file($uploaded_file)) { // initiate ftp $ret = ftp_nb_put($conn_id, $file_path, $uploaded_file, FTP_BINARY, FTP_AUTORESUME); while ($ret == FTP_MOREDATA) { // continue uploading $ret = ftp_nb_continue($conn_id); } if ($ret != FTP_FINISHED) { $fileUpload->error = 'There was a problem uploading the file to ' . $uploadServerDetails['ipAddress']; } else { $file_size = filesize($uploaded_file); @unlink($uploaded_file); } } } // close ftp connection ftp_close($conn_id); } else { // create the upload folder $uploadPathDir = $this->options['upload_dir'] . substr($newFilename, 0, 2); @mkdir($uploadPathDir); $file_path = $uploadPathDir . '/' . $newFilename; clearstatcache(); if ($uploaded_file && is_uploaded_file($uploaded_file)) { move_uploaded_file($uploaded_file, $file_path); } $file_size = filesize($file_path); } // check filesize uploaded matches tmp uploaded if ($file_size === $fileUpload->size) { $fileUpload->url = $this->options['upload_url'] . rawurlencode($fileUpload->name); // insert into the db $fileUpload->size = $file_size; $fileUpload->delete_url = '~d?' . $this->options['delete_hash']; $fileUpload->info_url = '~i?' . $this->options['delete_hash']; $fileUpload->delete_type = 'DELETE'; // create delete hash, make sure it's unique $deleteHash = md5($fileUpload->name . getUsersIPAddress() . microtime()); $existingFile = file::loadByDeleteHash($deleteHash); while ($existingFile != false) { $deleteHash = md5($fileUpload->name . getUsersIPAddress() . microtime()); $existingFile = file::loadByDeleteHash($deleteHash); } // store in db $db = Database::getDatabase(true); $dbInsert = new DBObject("file", array("originalFilename", "shortUrl", "fileType", "extension", "fileSize", "localFilePath", "userId", "totalDownload", "uploadedIP", "uploadedDate", "statusId", "deleteHash", "serverId")); $dbInsert->originalFilename = $fileUpload->name; $dbInsert->shortUrl = 'temp'; $dbInsert->fileType = $fileUpload->type; $dbInsert->extension = $extension; $dbInsert->fileSize = $fileUpload->size; $dbInsert->localFilePath = substr($file_path, strlen($this->options['upload_dir']), 99999); // add user id if user is logged in $dbInsert->userId = NULL; $Auth = Auth::getAuth(); if ($Auth->loggedIn()) { $dbInsert->userId = (int) $Auth->id; } $dbInsert->totalDownload = 0; $dbInsert->uploadedIP = getUsersIPAddress(); $dbInsert->uploadedDate = sqlDateTime(); $dbInsert->statusId = 1; $dbInsert->deleteHash = $deleteHash; $dbInsert->serverId = $uploadServerId; if (!$dbInsert->insert()) { $fileUpload->error = 'abort'; } // create short url $tracker = 1; $shortUrl = file::createShortUrlPart($tracker . $dbInsert->id); $fileTmp = file::loadByShortUrl($shortUrl); while ($fileTmp) { $shortUrl = file::createShortUrlPart($tracker . $dbInsert->id); $fileTmp = file::loadByShortUrl($shortUrl); $tracker++; } // update short url file::updateShortUrl($dbInsert->id, $shortUrl); // update fileUpload with file location $file = file::loadByShortUrl($shortUrl); $fileUpload->url = $file->getFullShortUrl(); $fileUpload->delete_url = $file->getDeleteUrl(); $fileUpload->info_url = $file->getInfoUrl(); $fileUpload->stats_url = $file->getStatisticsUrl(); $fileUpload->short_url = $shortUrl; } else { if ($this->options['discard_aborted_uploads']) { //@TODO - made ftp compatible @unlink($file_path); @unlink($uploaded_file); if (!isset($fileUpload->error)) { $fileUpload->error = 'maxFileSize'; } } } } return $fileUpload; }
/** * * 存储一个文件至 FTP 服务器(non-blocking) * * @param string $remote_file * @param string $local_file * @param int $mode * @param int $startpos * @return int 返回 FTP_FAILED,FTP_FINISHED 或 FTP_MOREDATA */ public static function nbPut($remote_file, $local_file, $mode = FTP_ASCII, $startpos = 0) { return ftp_nb_put(self::$resource, $remote_file, $local_file, $mode, $startpos); }
public function put($local_file, $remote_file, $overwrite = false, $mode = null, $options = 0) { if ($options & (FILE_FTP_BLOCKING | FILE_FTP_NONBLOCKING) === (FILE_FTP_BLOCKING | FILE_FTP_NONBLOCKING)) { throw new FTPException("Bad options given: FILE_FTP_NONBLOCKING and '. 'FILE_FTP_BLOCKING can't both be set"); } $usenb = !($options & FILE_FTP_BLOCKING == FILE_FTP_BLOCKING); if (!isset($mode)) { $mode = $this->checkFileExtension($local_file); } $remote_file = $this->constructPath($remote_file); if (!file_exists($local_file)) { throw new FTPException("Local file '{$local_file}' does not exist."); } if (ftp_size($this->handle, $remote_file) != -1 && !$overwrite) { throw new FTPException("Remote file '" . $remote_file . "' exists and may not be overwriten."); } if (function_exists('ftp_alloc')) { ftp_alloc($this->handle, filesize($local_file)); } if ($usenb && function_exists('ftp_nb_put')) { $res = ftp_nb_put($this->handle, $remote_file, $local_file, $mode); while ($res == FTP_MOREDATA) { $res = ftp_nb_continue($this->handle); } } else { $res = ftp_put($this->handle, $remote_file, $local_file, $mode); } if (!$res) { throw new FTPException("File '{$local_file}' could not be uploaded to '" . $remote_file . "'."); } return true; }
/** * 将本地文件上传到FTP * * @params array $params 参数 array('local'=>'本地文件路径','remote'=>'远程文件路径','resume'=>'文件指针位置') * @params string $msg * * @return bool */ public function push($params, &$msg) { if ($this->ftp_extension) { try { $ret = ftp_nb_put($this->conn, $params['remote'], $params['local'], $this->mode, $params['resume']); while ($ret == FTP_MOREDATA) { $ret = ftp_nb_continue($this->conn); } } catch (Exception $e) { $ret = $e->getMessage(); } } else { $ret = $this->ftpclient->upload($params['local'], $params['remote'], $this->mode, $params['resume']); } if ($ret == FTP_FAILED || !$ret) { $msg = app::get('importexport')->_('上传失败返回信息 ' . var_export($ret, 1)); return false; } return true; }
function put_htaccess($ftp_handle, $dir, $content) { $local_htaccess = tempnam("files", "down"); $fd = @fopen($local_htaccess, "w"); if ($fd) { @fwrite($fd, $content); @fclose($fd); } @chmod($local_htaccess, 0644); // Загружаем файл .htaccess на сервер $ftp_name = str_replace("//", "/", $dir . '/.htaccess'); $ret = @ftp_nb_put($ftp_handle, $ftp_name, $local_htaccess, FTP_BINARY); while ($ret == FTP_MOREDATA) { // Продолжаем загрузку $ret = @ftp_nb_continue($ftp_handle); } if ($ret == FTP_FINISHED) { // Изменяем права доступа для только что // созданной директории @ftp_chmod($ftp_handle, 0644, $ftp_name); } @unlink($local_htaccess); }
protected function nb_put($remotefile, $localfile, $start = FTP_AUTORESUME) { $ret = @ftp_nb_put($this->connexion, $remotefile, $localfile, FTP_BINARY, $start); while ($ret === FTP_MOREDATA) { set_time_limit(20); $ret = ftp_nb_continue($this->connexion); } return $ret; }
/** * Processes any files awaiting to upload and attempts to begin the upload * transfer. * * @todo Add an emit for failure to connect, incorrect file. * * @return void */ protected function _init_transfers() { foreach ($this->_files as $_k => $_file) { if (!$_file instanceof File) { continue; } if ($this->_options['secure']) { $connection = ftp_ssl_connect($this->_options['hostname'], $this->_options['port'], $this->_options['timeout']); } else { $connection = ftp_connect($this->_options['hostname'], $this->_options['port'], $this->_options['timeout']); } if (false === $connection) { break; } $login = ftp_login($connection, $this->_options['username'], $this->_options['password']); if ($login === false) { $this->_sig_failure->set_upload($_file); xp_emit($this->_sig_failure, new SIG_Failure($_file)); ftp_close($connection); break; } if (!file_exists($_file->get_full_path())) { xp_emit($this->_sig_failure, new SIG_Failure($_file)); } else { $transfer = ftp_nb_put($connection, $_file->get_name(), $_file->get_full_path(), $_file->get_transfer_mode()); if ($transfer === FTP_MOREDATA) { $this->_uploading[] = [$connection, $_file]; } else { if ($transfer == FTP_FINISHED) { $this->_sig_complete->set_upload($_file); xp_emit($this->_sig_complete); // Close the FTP connection to that file ftp_close($connection); $this->_uploaded[] = $_file; } else { $this->_sig_failure->set_upload($_file); xp_emit($this->_sig_failure); // Close the FTP connection to that file ftp_close($connection); } } } unset($this->_files[$_k]); } }