search
HomeBackend DevelopmentPHP Tutorialphp script for ftp upload files

Rough principle Iterate through all non-excluded files in the project and get the files for 文件修改时间晚于文件上一次修改时间 Then upload these files to the corresponding directory via ftp The specific code is as follows:

Because it’s just a tool, the code is very messy, sorry

  1. error_reporting(7);
  2. if ($_SERVER['SERVER_ADDR'])exit;//It is forbidden to run under the web server
  3. $_GET['exclude'] = array('number.txt ','uploads','Zend','docs','cache','You','managesdk'); //Exclude upload directory, defined as a global variable
  4. $fileobj = new FilerFile();
  5. $path = "/data/longtu/"; //The root directory of the project directory
  6. $files = $fileobj->Zip($path); //Filter out the latest modified files
  7. $path = str_replace("/data/longtu/ ","",$path);
  8. $config = array(
  9. 'hostname' => 'xxx.xxx.xx.xxx', //ftp server address
  10. 'username' => 'xxx', // ftp user
  11. 'password' => '?xxxxxxxxxxx', //ftp password
  12. 'port' => 21 //Port
  13. );
  14. $ftp = new Ftp();
  15. $ftp->connect($ config); //Linked server
  16. //$a=$ftp->filelist();
  17. $LOCAL_ROOT = realpath(dirname(__DIR__)."/../../");
  18. chdir($LOCAL_ROOT) ;
  19. foreach ($files as $k=>$v){
  20. $f = $path.$v;
  21. $tmp = $ftp->upload($f, $f);
  22. if($tmp) {
  23. echo "upload $f -> success n";
  24. }
  25. }
  26. //$ftp->download('ftp_upload.log','ftp_download.log');
  27. //
  28. //$ftp- >upload('ftp_err.log','ftp_upload.log');
  29. //$ftp->download('ftp_upload.log','ftp_download.log');
  30. /*
  31. *
  32. *
  33. * $ dir = "/test";
  34. if(@ftp_chdir($conn, $dir))
  35. Determine whether it is a folder
  36. * Enter description here ...
  37. * @author Administrator
  38. *
  39. */
  40. class FilerFile
  41. {
  42. var $time_path;
  43. private $fctimes = array();
  44. function Zip($dir)
  45. {
  46. $this->time_path = rtrim($dir,"/")."/.~~~time.php" ;
  47. //@unlink($this->time_path);
  48. $filelist = $this -> GetFileList($dir);
  49. file_put_contents($this->time_path,"fctimes,true).";");
  50. return $filelist;
  51. }
  52. function appendFiletime($file)
  53. {
  54. $time_file_path = $this->time_path;
  55. $ftime = @include( $time_file_path);
  56. $ftime = $ftime ? $ftime : array();
  57. $time = filectime($file);
  58. if(!file_exists($time_file_path))file_put_contents($time_file_path," }
  59. function getFileByFiletime($file)
  60. {
  61. static $time_data ;
  62. $time_file_path = $this->time_path;
  63. if (!$time_data){
  64. $time_data= @include_once($time_file_path);
  65. }
  66. $time_data = $time_data ? $time_data : array();
  67. //var_dump($file,$time_data[$file] == filectime($file));
  68. //echo $file."t".$time_data [$file]."n";
  69. if ($time_data[$file] == filemtime($file)){
  70. return false;
  71. }else{
  72. return $file;
  73. }
  74. }
  75. function GetFileList($dir ,$path="")
  76. {
  77. static $tmpp = "";
  78. if ($path=="" && !$tmpp){
  79. $tmpp = $dir;
  80. }
  81. $d = dir($dir) ;
  82. $files = array();
  83. if ($d)
  84. {
  85. $pathP=str_replace($tmpp,"",$dir);
  86. $pathP=str_replace(array("\\","/") ,DIRECTORY_SEPARATOR,$pathP);
  87. $pathP=str_replace(DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR,DIRECTORY_SEPARATOR,$pathP);
  88. while($f = $d->read())
  89. {
  90. if ($f == '.' || $f=='..' || $f{0}=='.' || $f=='Zend' || in_array($f, $_GET['exclude']))continue;
  91. $newdir = rtrim($dir,"/")."/".$f;
  92. if (is_dir($newdir)){
  93. $files = array_merge($files,$this->GetFileList($newdir,$ newdir));
  94. }else{
  95. $abspath_file = (rtrim($dir,"/") ? rtrim($dir,"/")."/" : "").$f;
  96. $this-> fctimes[$abspath_file] = filemtime($abspath_file);
  97. if (!$this->getFileByFiletime($abspath_file))continue;
  98. $file = (rtrim($pathP,"/") ? rtrim($pathP," /")."/" : "").$f;
  99. $files[] = $file;
  100. }
  101. }
  102. }
  103. return $files;
  104. }
  105. }
  106. /**
  107. * Imitate CodeIgniter's FTP class
  108. * Basic FTP operations:
  109. * 1) Log in; connect
  110. * 2) Current directory file list; filelist
  111. * 3) Directory change; chgdir
  112. * 4) Rename/move; rename
  113. * 5) Create folder; mkdir
  114. * 6) Delete; delete_dir/delete_file
  115. * 7) Upload; upload
  116. * 8) Download download
  117. *
  118. * @author quanshuidingdang
  119. */
  120. class Ftp {
  121. private $hostname = '';
  122. private $username = '';
  123. private $password = '';
  124. private $port = 21;
  125. private $passive = TRUE;
  126. private $debug = TRUE;
  127. private $conn_id = FALSE;
  128. /**
  129. * Constructor
  130. *
  131. * @param array Configuration array: $config = array('hostname'=>'','username'=>'','password'=>'','port'= >''...);
  132. */
  133. public function __construct($config = array()) {
  134. if(count($config) > 0) {
  135. $this->_init($config);
  136. }
  137. }
  138. /**
  139. * FTP connection
  140. *
  141. * @access public
  142. * @param array configuration array
  143. * @return boolean
  144. */
  145. public function connect($config = array()) {
  146. if(count($config) > 0) {
  147. $this->_init($config);
  148. }
  149. if(FALSE === ($this->conn_id = @ftp_connect($this->hostname,$this->port))) {
  150. if($this->debug === TRUE) {
  151. $this->_error("ftp_unable_to_connect");
  152. }
  153. return FALSE;
  154. }
  155. if( ! $this->_login()) {
  156. if($this->debug === TRUE) {
  157. $this->_error("ftp_unable_to_login");
  158. }
  159. return FALSE;
  160. }
  161. if($this->passive === TRUE) {
  162. ftp_pasv($this->conn_id, TRUE);
  163. }
  164. return TRUE;
  165. }
  166. /**
  167. * Whether the folder exists
  168. * @param unknown_type $path
  169. */
  170. public function is_dir_exists($path)
  171. {
  172. return $this->chgdir($path);
  173. }
  174. /**
  175. * Directory change
  176. *
  177. * @access public
  178. * @param string directory identification (ftp)
  179. * @param boolean
  180. * @return boolean
  181. */
  182. public function chgdir($path = '', $supress_debug = FALSE) {
  183. if($path == '' OR ! $this->_isconn()) {
  184. return FALSE;
  185. }
  186. $result = @ftp_chdir($this->conn_id, $path);
  187. if($result === FALSE) {
  188. if($this->debug === TRUE AND $supress_debug == FALSE) {
  189. $this->_error("ftp_unable_to_chgdir:dir[".$path."]");
  190. }
  191. return FALSE;
  192. }
  193. return TRUE;
  194. }
  195. /**
  196. * Directory generation
  197. *
  198. * @access public
  199. * @param string directory identification (ftp)
  200. * @param int file permission list
  201. * @return boolean
  202. */
  203. public function mkdir($path = '', $permissions = NULL) {
  204. if($path == '' OR ! $this->_isconn()) {
  205. return FALSE;
  206. }
  207. $result = @ftp_mkdir($this->conn_id, $path);
  208. if($result === FALSE) {
  209. if($this->debug === TRUE) {
  210. $this->_error("ftp_unable_to_mkdir:dir[".$path."]");
  211. }
  212. return FALSE;
  213. }
  214. if( ! is_null($permissions)) {
  215. $this->chmod($path,(int)$permissions);
  216. }
  217. return TRUE;
  218. }
  219. /**
  220. * Upload
  221. *
  222. * @access public
  223. * @param string local directory identifier
  224. * @param string remote directory identifier (ftp)
  225. * @param string upload mode auto || ascii
  226. * @param int file permissions after uploading List
  227. * @return boolean
  228. */
  229. public function upload($localpath, $remotepath, $mode = 'auto', $permissions = NULL) {
  230. if( ! $this->_isconn()) {
  231. return FALSE;
  232. }
  233. if( ! file_exists($localpath)) {
  234. if($this->debug === TRUE) {
  235. $this->_error("ftp_no_source_file:".$localpath);
  236. }
  237. return FALSE;
  238. }
  239. if($mode == 'auto') {
  240. $ext = $this->_getext($localpath);
  241. $mode = $this->_settype($ext);
  242. }
  243. $mode = ($mode == 'ascii') ? FTP_ASCII : FTP_BINARY;
  244. $result = @ftp_put($this->conn_id, $remotepath, $localpath, $mode);
  245. if($result === FALSE) {
  246. if($this->debug === TRUE) {
  247. $this->_error("ftp_unable_to_upload:localpath[".$localpath."]/remotepath[".$remotepath."]");
  248. }
  249. return FALSE;
  250. }
  251. if( ! is_null($permissions)) {
  252. $this->chmod($remotepath,(int)$permissions);
  253. }
  254. return TRUE;
  255. }
  256. /**
  257. * Download
  258. *
  259. * @access public
  260. * @param string remote directory identification (ftp)
  261. * @param string local directory identification
  262. * @param string download mode auto || ascii
  263. * @return boolean
  264. */
  265. public function download($remotepath, $localpath, $mode = 'auto') {
  266. if( ! $this->_isconn()) {
  267. return FALSE;
  268. }
  269. if($mode == 'auto') {
  270. $ext = $this->_getext($remotepath);
  271. $mode = $this->_settype($ext);
  272. }
  273. $mode = ($mode == 'ascii') ? FTP_ASCII : FTP_BINARY;
  274. $result = @ftp_get($this->conn_id, $localpath, $remotepath, $mode);
  275. if($result === FALSE) {
  276. if($this->debug === TRUE) {
  277. $this->_error("ftp_unable_to_download:localpath[".$localpath."]-remotepath[".$remotepath."]");
  278. }
  279. return FALSE;
  280. }
  281. return TRUE;
  282. }
  283. /**
  284. * Rename/Move
  285. *
  286. * @access public
  287. * @param string Remote directory identification (ftp)
  288. * @param string New directory identification
  289. * @param boolean Determine whether to rename (FALSE) or move (TRUE)
  290. * @return boolean
  291. */
  292. public function rename($oldname, $newname, $move = FALSE) {
  293. if( ! $this->_isconn()) {
  294. return FALSE;
  295. }
  296. $result = @ftp_rename($this->conn_id, $oldname, $newname);
  297. if($result === FALSE) {
  298. if($this->debug === TRUE) {
  299. $msg = ($move == FALSE) ? "ftp_unable_to_rename" : "ftp_unable_to_move";
  300. $this->_error($msg);
  301. }
  302. return FALSE;
  303. }
  304. return TRUE;
  305. }
  306. /**
  307. * Delete file
  308. *
  309. * @access public
  310. * @param string file identifier (ftp)
  311. * @return boolean
  312. */
  313. public function delete_file($file) {
  314. if( ! $this->_isconn()) {
  315. return FALSE;
  316. }
  317. $result = @ftp_delete($this->conn_id, $file);
  318. if($result === FALSE) {
  319. if($this->debug === TRUE) {
  320. $this->_error("ftp_unable_to_delete_file:file[".$file."]");
  321. }
  322. return FALSE;
  323. }
  324. return TRUE;
  325. }
  326. /**
  327. * Delete folder
  328. *
  329. * @access public
  330. * @param string directory identifier (ftp)
  331. * @return boolean
  332. */
  333. public function delete_dir($path) {
  334. if( ! $this->_isconn()) {
  335. return FALSE;
  336. }
  337. //对目录宏的'/'字符添加反斜杠''
  338. $path = preg_replace("/(.+?)/*$/", "\1/", $path);
  339. //获取目录文件列表
  340. $filelist = $this->filelist($path);
  341. if($filelist !== FALSE AND count($filelist) > 0) {
  342. foreach($filelist as $item) {
  343. //如果我们无法删除,那么就可能是一个文件夹
  344. //所以我们递归调用delete_dir()
  345. if( ! @delete_file($item)) {
  346. $this->delete_dir($item);
  347. }
  348. }
  349. }
  350. //删除文件夹(空文件夹)
  351. $result = @ftp_rmdir($this->conn_id, $path);
  352. if($result === FALSE) {
  353. if($this->debug === TRUE) {
  354. $this->_error("ftp_unable_to_delete_dir:dir[".$path."]");
  355. }
  356. return FALSE;
  357. }
  358. return TRUE;
  359. }
  360. /**
  361. * Modify file permissions
  362. *
  363. * @access public
  364. * @param string directory identification (ftp)
  365. * @return boolean
  366. */
  367. public function chmod($path, $perm) {
  368. if( ! $this->_isconn()) {
  369. return FALSE;
  370. }
  371. //只有在PHP5中才定义了修改权限的函数(ftp)
  372. if( ! function_exists('ftp_chmod')) {
  373. if($this->debug === TRUE) {
  374. $this->_error("ftp_unable_to_chmod(function)");
  375. }
  376. return FALSE;
  377. }
  378. $result = @ftp_chmod($this->conn_id, $perm, $path);
  379. if($result === FALSE) {
  380. if($this->debug === TRUE) {
  381. $this->_error("ftp_unable_to_chmod:path[".$path."]-chmod[".$perm."]");
  382. }
  383. return FALSE;
  384. }
  385. return TRUE;
  386. }
  387. /**
  388. * Get directory file list
  389. *
  390. * @access public
  391. * @param string directory identification (ftp)
  392. * @return array
  393. */
  394. public function filelist($path = '.') {
  395. if( ! $this->_isconn()) {
  396. return FALSE;
  397. }
  398. return ftp_nlist($this->conn_id, $path);
  399. }
  400. /**
  401. * Close FTP
  402. *
  403. * @access public
  404. * @return boolean
  405. */
  406. public function close() {
  407. if( ! $this->_isconn()) {
  408. return FALSE;
  409. }
  410. return @ftp_close($this->conn_id);
  411. }
  412. /**
  413. * FTP member variable initialization
  414. *
  415. * @access private
  416. * @param array configuration array
  417. * @return void
  418. */
  419. private function _init($config = array()) {
  420. foreach($config as $key => $val) {
  421. if(isset($this->$key)) {
  422. $this->$key = $val;
  423. }
  424. }
  425. //特殊字符过滤
  426. $this->hostname = preg_replace('|.+?://|','',$this->hostname);
  427. }
  428. /**
  429. * FTP login
  430. *
  431. * @access private
  432. * @return boolean
  433. */
  434. private function _login() {
  435. return @ftp_login($this->conn_id, $this->username, $this->password);
  436. }
  437. /**
  438. * Judge con_id
  439. *
  440. * @access private
  441. * @return boolean
  442. */
  443. private function _isconn() {
  444. if( ! is_resource($this->conn_id)) {
  445. if($this->debug === TRUE) {
  446. $this->_error("ftp_no_connection");
  447. }
  448. return FALSE;
  449. }
  450. return TRUE;
  451. }
  452. /**
  453. * Get the suffix extension from the file name
  454. *
  455. * @access private
  456. * @param string directory identifier
  457. * @return string
  458. */
  459. private function _getext($filename) {
  460. if(FALSE === strpos($filename, '.')) {
  461. return 'txt';
  462. }
  463. $extarr = explode('.', $filename);
  464. return end($extarr);
  465. }
  466. /**
  467. * Define FTP transfer mode ascii or binary from suffix extension
  468. *
  469. * @access private
  470. * @param string suffix extension
  471. * @return string
  472. */
  473. private function _settype($ext) {
  474. $text_type = array (
  475. 'txt',
  476. 'text',
  477. 'php',
  478. 'phps',
  479. 'php4',
  480. 'js',
  481. 'css',
  482. 'htm',
  483. 'html',
  484. 'phtml',
  485. 'shtml',
  486. 'log',
  487. 'xml'
  488. );
  489. return (in_array($ext, $text_type)) ? 'ascii' : 'binary';
  490. }
  491. /**
  492. * Error logging
  493. *
  494. * @access prvate
  495. * @return boolean
  496. */
  497. private function _error($msg) {
  498. return @file_put_contents('/tmp/ftp_err.log', "date[".date("Y-m-d H:i:s")."]-hostname[".$this->hostname."]-username[".$this->username."]-password[".$this->password."]-msg[".$msg."]n", FILE_APPEND);
  499. }
  500. }
  501. /*End of file ftp.php*/
  502. /*Location /Apache Group/htdocs/ftp.php*/
复制代码

上传文件, ftp, php


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in LaravelNotifications in LaravelMar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft