Maison développement back-end tutoriel php ftp上传文件的php脚本

ftp上传文件的php脚本

Jul 25, 2016 am 08:42 AM

大概原理 遍历项目中的所有非排除文件,然后获取 文件修改时间晚于文件上一次修改时间 的文件 然后将这些文件,通过ftp上传到对应的目录 具体代码如下:

因为只是工具,代码很乱,见谅

  1. error_reporting(7);
  2. if ($_SERVER['SERVER_ADDR'])exit;//禁止在web服务器下运行
  3. $_GET['exclude'] = array('number.txt','uploads','Zend','docs','cache','You','managesdk'); //排除上传目录,定义为全局变量
  4. $fileobj = new FilerFile();
  5. $path = "/data/longtu/"; //项目目录的根目录
  6. $files = $fileobj->Zip($path); //过滤出最新的修改文件
  7. $path = str_replace("/data/longtu/","",$path);
  8. $config = array(
  9. 'hostname' => 'xxx.xxx.xx.xxx', //ftp服务器 地址
  10. 'username' => 'xxx', //ftp用户
  11. 'password' => '?xxxxxxxxxxx', //ftp密码
  12. 'port' => 21 //端口
  13. );
  14. $ftp = new Ftp();
  15. $ftp->connect($config); //链接服务器
  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. 判断是否为文件夹
  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 appendFilectime($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 getFileByFilectime($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->getFileByFilectime($abspath_file))continue;
  98. $file = (rtrim($pathP,"/") ? rtrim($pathP,"/")."/" : "").$f;
  99. $files[] = $file;
  100. }
  101. }
  102. }
  103. return $files;
  104. }
  105. }
  106. /**
  107. * 仿写CodeIgniter的FTP类
  108. * FTP基本操作:
  109. * 1) 登陆; connect
  110. * 2) 当前目录文件列表; filelist
  111. * 3) 目录改变; chgdir
  112. * 4) 重命名/移动; rename
  113. * 5) 创建文件夹; mkdir
  114. * 6) 删除; delete_dir/delete_file
  115. * 7) 上传; upload
  116. * 8) 下载 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. * 构造函数
  130. *
  131. * @param 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连接
  140. *
  141. * @access public
  142. * @param 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. * 文件夹是否存在
  168. * @param unknown_type $path
  169. */
  170. public function is_dir_exists($path)
  171. {
  172. return $this->chgdir($path);
  173. }
  174. /**
  175. * 目录改变
  176. *
  177. * @access public
  178. * @param string 目录标识(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. * 目录生成
  197. *
  198. * @access public
  199. * @param string 目录标识(ftp)
  200. * @param int 文件权限列表
  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. * 上传
  221. *
  222. * @access public
  223. * @param string 本地目录标识
  224. * @param string 远程目录标识(ftp)
  225. * @param string 上传模式 auto || ascii
  226. * @param int 上传后的文件权限列表
  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. * 下载
  258. *
  259. * @access public
  260. * @param string 远程目录标识(ftp)
  261. * @param string 本地目录标识
  262. * @param string 下载模式 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. * 重命名/移动
  285. *
  286. * @access public
  287. * @param string 远程目录标识(ftp)
  288. * @param string 新目录标识
  289. * @param boolean 判断是重命名(FALSE)还是移动(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. * 删除文件
  308. *
  309. * @access public
  310. * @param string 文件标识(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. * 删除文件夹
  328. *
  329. * @access public
  330. * @param string 目录标识(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. * 修改文件权限
  362. *
  363. * @access public
  364. * @param string 目录标识(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. * 获取目录文件列表
  389. *
  390. * @access public
  391. * @param string 目录标识(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. * 关闭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成员变量初始化
  414. *
  415. * @access private
  416. * @param 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登陆
  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. * 判断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. * 从文件名中获取后缀扩展
  454. *
  455. * @access private
  456. * @param string 目录标识
  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. * 从后缀扩展定义FTP传输模式 ascii 或 binary
  468. *
  469. * @access private
  470. * @param string 后缀扩展
  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. * 错误日志记录
  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


Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Meilleurs paramètres graphiques
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Comment réparer l'audio si vous n'entendez personne
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: Comment déverrouiller tout dans Myrise
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Travailler avec les données de session Flash dans Laravel Travailler avec les données de session Flash dans Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifie la gestion des données de session temporaires à l'aide de ses méthodes de flash intuitives. Ceci est parfait pour afficher de brefs messages, alertes ou notifications dans votre application. Les données ne persistent que pour la demande ultérieure par défaut: $ demande-

Curl dans PHP: Comment utiliser l'extension PHP Curl dans les API REST Curl dans PHP: Comment utiliser l'extension PHP Curl dans les API REST Mar 14, 2025 am 11:42 AM

L'extension PHP Client URL (CURL) est un outil puissant pour les développeurs, permettant une interaction transparente avec des serveurs distants et des API REST. En tirant parti de Libcurl, une bibliothèque de transfert de fichiers multi-protocol très respectée, PHP Curl facilite Efficient Execu

Misque de réponse HTTP simplifié dans les tests Laravel Misque de réponse HTTP simplifié dans les tests Laravel Mar 12, 2025 pm 05:09 PM

Laravel fournit une syntaxe de simulation de réponse HTTP concise, simplifiant les tests d'interaction HTTP. Cette approche réduit considérablement la redondance du code tout en rendant votre simulation de test plus intuitive. L'implémentation de base fournit une variété de raccourcis de type de réponse: Utiliser illuminate \ support \ faades \ http; Http :: faux ([[ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 meilleurs scripts de chat PHP sur Codecanyon 12 meilleurs scripts de chat PHP sur Codecanyon Mar 13, 2025 pm 12:08 PM

Voulez-vous fournir des solutions instantanées en temps réel aux problèmes les plus pressants de vos clients? Le chat en direct vous permet d'avoir des conversations en temps réel avec les clients et de résoudre leurs problèmes instantanément. Il vous permet de fournir un service plus rapide à votre personnalité

Expliquez le concept de liaison statique tardive en PHP. Expliquez le concept de liaison statique tardive en PHP. Mar 21, 2025 pm 01:33 PM

L'article traite de la liaison statique tardive (LSB) dans PHP, introduite dans PHP 5.3, permettant une résolution d'exécution de la méthode statique nécessite un héritage plus flexible. Problème main: LSB vs polymorphisme traditionnel; Applications pratiques de LSB et perfo potentiel

Frameworks de personnalisation / d'extension: comment ajouter des fonctionnalités personnalisées. Frameworks de personnalisation / d'extension: comment ajouter des fonctionnalités personnalisées. Mar 28, 2025 pm 05:12 PM

L'article examine l'ajout de fonctionnalités personnalisées aux cadres, en se concentrant sur la compréhension de l'architecture, l'identification des points d'extension et les meilleures pratiques pour l'intégration et le débogage.

Comment envoyer une demande post contenant des données JSON à l'aide de la bibliothèque Curl de PHP? Comment envoyer une demande post contenant des données JSON à l'aide de la bibliothèque Curl de PHP? Apr 01, 2025 pm 03:12 PM

Envoyant des données JSON à l'aide de la bibliothèque Curl de PHP dans le développement de PHP, il est souvent nécessaire d'interagir avec les API externes. L'une des façons courantes consiste à utiliser la bibliothèque Curl pour envoyer le post� ...

See all articles