Home Backend Development PHP Tutorial php script for ftp upload files

php script for ftp upload files

Jul 25, 2016 am 08:42 AM

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles