首頁 後端開發 php教程 ftp上傳檔案的php腳本

ftp上傳檔案的php腳本

Jul 25, 2016 am 08:42 AM

대략적인 원리 프로젝트에서 제외되지 않은 모든 파일을 반복하고 文件修改时间晚于文件上一次修改时间에 대한 파일을 가져옵니다. 그런 다음 FTP를 통해 해당 파일을 해당 디렉토리에 업로드하십시오. 구체적인 코드는 다음과 같습니다.

도구일 뿐이라 코드가 너무 지저분하네요 죄송합니다

  1. error_reporting(7);
  2. if ($_SERVER['SERVER_ADDR'])exit;//웹 서버에서 실행이 금지됩니다
  3. $_GET['exclude'] = array('number.txt','uploads','Zend','docs','cache','You','managesdk') //전역으로 정의된 업로드 디렉터리 제외 Variable
  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); //링크 서버 $a=$ftp->filelist();
  16. $LOCAL_ROOT = realpath(dirname(__DIR__)."/../../");
  17. chdir($LOCAL_ROOT);
  18. foreach( $files as $k=>$v){
  19. $f = $path.$v;
  20. $tmp = $ftp->upload($f, $f);
  21. if($ tmp){
  22. echo "$f 업로드 -> 성공 n";
  23. }
  24. }
  25. //$ftp->download('ftp_upload.log','ftp_download.log') ;
  26. //
  27. //$ftp->upload('ftp_err.log','ftp_upload.log');
  28. //$ftp->download('ftp_upload.log',' ftp_download.log');
  29. /*
  30. *
  31. *
  32. * $dir = "/test";
  33. if(@ftp_chdir($conn, $dir))
  34. 판단 폴더인가요? $fctimes = array();
  35. function Zip($dir)
  36. {
  37. $this->time_path = rtrim($dir,"/")."/.~~ ~time.php" ;
  38. //@unlink($this->time_path);
  39. $filelist = $this -> GetFileList($dir);
  40. file_put_contents($this->time_path ,"fctimes,true).";");
  41. return $filelist;
  42. }
  43. function appendFiletime($file)
  44. {
  45. $ time_file_path = $this->time_path;
  46. $ftime = @include($time_file_path);
  47. $ftime = $ftime ? $ftime : array();
  48. $time = filectime ($file);
  49. if(!file_exists($time_file_path))file_put_contents($time_file_path," }
  50. function getFileByFiletime($file)
  51. {
  52. static $time_data;
  53. $time_file_path = $this->time_path;
  54. if (!$time_data){
  55. $time_data= @include_once($time_file_path);
  56. }
  57. $time_data = $time_data ? $ time_data : array();
  58. //var_dump($file,$time_data[$file] == filectime($file));
  59. //echo $file."t".$ time_data[$file] ."n";
  60. if ($time_data[$file] == filemtime($file)){
  61. return false;
  62. }else{
  63. return $file;
  64. }
  65. }
  66. function GetFileList($dir,$path="")
  67. {
  68. static $tmpp = "";
  69. if ($path=="" && !$ tmpp){
  70. $tmpp = $dir;
  71. }
  72. $d = dir($dir);
  73. $files = array();
  74. if ($d)
  75. {
  76. $pathP =str_replace($tmpp,"",$dir);
  77. $pathP=str_replace(array("\\","/"),DIRECTORY_SEPARATOR,$pathP);
  78. $pathP= str_replace(DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR ,DIRECTORY_SEPARATOR,$pathP);
  79. while($f = $d->read())
  80. {
  81. if ($f == '.' || $f= ='..' || $f{0}=='.' || $f=='Zend' || in_array($f, $_GET['exclude']))계속;
  82. $newdir = rtrim($dir, "/")."/".$f;
  83. if (is_dir($newdir)){
  84. $files = array_merge($files,$this->GetFileList($newdir, $newdir));
  85. }else{
  86. $abspath_file = (rtrim($dir,"/") ? rtrim($dir,"/")."/" : "").$f;
  87. $this- >fctimes[$abspath_file] = filemtime($abspath_file);
  88. if (!$this->getFileByFiletime($abspath_file))continue;
  89. $file = (rtrim($pathP, "/") ? rtrim($pathP,"/")."/" : "").$f;
  90. $files[] = $file;
  91. }
  92. }
  93. }
  94. $files 반환 ;
  95. }
  96. }
  97. /**
  98. * CodeIgniter의 FTP 클래스 모방
  99. * 기본 FTP 작업:
  100. * 1) 로그인; 연결
  101. * 2) 현재 디렉터리 파일 목록
  102. * 3) 디렉터리 변경; > * 4) 이름 바꾸기/이동, 이름 바꾸기
  103. * 5) mkdir
  104. * 6) 삭제; delete_dir/delete_file
  105. * 7) 업로드; 다운로드
  106. *
  107. * @author quanshuidingdang
  108. */
  109. class Ftp {
  110. private $hostname = '';
  111. private $username = '';
  112. private $password = '';
  113. private $port = 21;
  114. private $passive = TRUE;
  115. private $debug = TRUE;
  116. private $conn_id = FALSE;
  117. /**
  118. * 생성자
  119. *
  120. * @param array 구성 배열: $config = array('hostname'=>'','username'=>'','password'=>' ' ,'포트'=>''...);
  121. */
  122. 공용 함수 __construct ($config = array()) {
  123. if(count($config) > 0) {
  124. $this->_init($config);
  125. }
  126. }
  127. / **
  128. * FTP 연결
  129. *
  130. * @access public
  131. * @param 배열 구성 배열
  132. * @return boolean
  133. */
  134. 공용 함수 connect($config = array()) {
  135. if(count($config) > 0) {
  136. $this->_init($config) ;
  137. }
  138. if(FALSE === ($this->conn_id = @ftp_connect($this->hostname,$this->port))) {
  139. if($this- >debug === TRUE) {
  140. $this->_error("ftp_unable_to_connect");
  141. }
  142. return FALSE;
  143. }
  144. if( ! $this->_login ()) {
  145. if($this->debug === TRUE) {
  146. $this->_error("ftp_unable_to_login");
  147. }
  148. return FALSE;
  149. }
  150. if($this->passive === TRUE) {
  151. ftp_pasv($this->conn_id, TRUE);
  152. }
  153. return TRUE;
  154. }
  155. / **
  156. * 폴더 존재 여부
  157. * @paramknown_type $path
  158. */
  159. 공개 함수 is_dir_exists($path)
  160. {
  161. return $this->chgdir($path);
  162. }
  163. /**
  164. * 디렉터리 변경
  165. *
  166. * @access public
  167. * @param 문자열 디렉터리 식별(ftp)
  168. * @param boolean
  169. * @return boolean
  170. * /
  171. 공용 함수 chgdir($path = '', $supress_debug = FALSE) {
  172. if($path == '' OR ! $this->_isconn()) {
  173. return FALSE;
  174. }
  175. $result = @ftp_chdir($this->conn_id, $path);
  176. if($result === 거짓) {
  177. if($this->debug === TRUE AND $supress_debug == FALSE) {
  178. $this->_error("ftp_unable_to_chgdir:dir[".$path."]") ;
  179. }
  180. FALSE 반환;
  181. }
  182. TRUE 반환;
  183. }
  184. /**
  185. * 디렉터리 생성
  186. *
  187. * @access public
  188. * @param 문자열 디렉터리 식별(ftp)
  189. * @param int 파일 권한 목록
  190. * @return 부울
  191. */
  192. 공용 함수 mkdir($path = '', $ 권한 = NULL) {
  193. if($path == '' OR ! $this->_isconn()) {
  194. return FALSE;
  195. }
  196. $result = @ftp_mkdir($this- >conn_id, $path);
  197. if($result === FALSE) {
  198. if($this->debug === TRUE) {
  199. $this->_error("ftp_unable_to_mkdir :dir[".$path."]");
  200. }
  201. return FALSE;
  202. }
  203. if( ! is_null($permissions)) {
  204. $this->chmod( $path,(int)$permissions);
  205. }
  206. return TRUE;
  207. }
  208. /**
  209. * 업로드
  210. *
  211. * @access public
  212. * @param string 로컬 디렉터리 ID
  213. * @param string 원격 디렉터리 ID(ftp)
  214. * @param 문자열 업로드 모드 자동 | | ascii
  215. * @param int 업로드 후 파일 권한 목록
  216. * @return boolean
  217. */
  218. 공개 함수 업로드($localpath, $remotepath, $mode = 'auto', $permissions = NULL) {
  219. if( !$this->_isconn()) {
  220. return FALSE;
  221. }
  222. if( ! file_exists($localpath)) {
  223. if($this->debug === TRUE) {
  224. $this->_error("ftp_no_source_file:".$localpath);
  225. }
  226. return FALSE;
  227. }
  228. if($mode == 'auto') {
  229. $ext = $this->_getext($localpath);
  230. $mode = $this->_settype ($ext);
  231. }
  232. $mode = ($mode == 'ascii') ? FTP_ASCII : FTP_BINARY;
  233. $result = @ftp_put($this->conn_id, $remotepath, $localpath, $mode);
  234. if($result === FALSE) {
  235. if($this ->디버그 === TRUE) {
  236. $this->_error("ftp_unable_to_upload:localpath[".$localpath."]/remotepath[".$remotepath."]");
  237. }
  238. FALSE 반환;
  239. }
  240. if( ! is_null($permissions)) {
  241. $this->chmod($remotepath,(int)$permissions);
  242. }
  243. 반환 그렇습니다.
  244. }
  245. /**
  246. * 下載
  247. *
  248. * @access public
  249. * @param string 遠端目錄識別(ftp)
  250. * @param string 本機目錄識別
  251. * @param string 下載模式模式模式 | | ascii
  252. * @return boolean
  253. */
  254. public function download($remotepath, $localpath, $mode = 'auto') {
  255. if( ! $this->_isconn()) {
  256. return FALSE;
  257. }
  258. if($mode == 'auto') {
  259. $ext = $this->_getext($remotepath);
  260. $mode = $this->; _settype($ext);
  261. }
  262. $mode = ($mode == 'ascii') ? FTP_ASCII : FTP_BINARY;
  263. $result = @ftp_get($this->conn_id, $localpath, $remotepath, $mode);
  264. if($result === FALSE) {
  265. if($this - >debug === TRUE) {
  266. $this->_error("ftp_unable_to_download:localpath[".$localpath."]-remotepath[".$remotepath."]");
  267. }
  268. return FALSE;
  269. }
  270. return TRUE;
  271. }
  272. /**
  273. * 重新命名/移動
  274. *
  275. * @access public
  276. * @param string 遠端目錄識別(ftp)
  277. * @param string 新目錄識別碼
  278. * @param boolean 判斷是重新命名(FALSE)還是移動(TRUE)
  279. * @return boolean
  280. */
  281. public function rename($oldname, $newname, $move = FALSE) {
  282. if ( ! $this->_isconn()) {
  283. return FALSE;
  284. }
  285. $result = @ftp_rename($this->conn_id, $oldname, $newname);
  286. if($result === FALSE) {
  287. if($this->debug === TRUE) {
  288. $msg = ($move == FALSE) ? "ftp_unable_to_rename" : "ftp_unable_to_move";
  289. $this->_error($msg);
  290. }
  291. 返回 FALSE;
  292. }
  293. 返回 TRUE;
  294. }
  295. / * *
  296. * 刪除檔案
  297. *
  298. * @access public
  299. * @param string 檔案識別(ftp)
  300. * @return boolean
  301. */
  302. public function delete_file($file) {
  303. if( ! $this->_isconn()) {
  304. return FALSE;
  305. }
  306. $result = @ftp_delete ($this->conn_id, $file);
  307. if($result === FALSE) {
  308. if($this->debug === TRUE) {
  309. $this- >_error(" ftp_unable_to_delete_file:file[".$file."]");
  310. }
  311. 回傳FALSE;
  312. }
  313. 回傳TRUE;
  314. }
  315. /**
  316. * 刪除資料夾
  317. *
  318. * @access public
  319. * @param string 目錄識別(ftp)
  320. * @return boolean
  321. * 🎜> public function delete_dir($path) {
  322. if( ! $this->_isconn()) {
  323. return FALSE;
  324. }
  325. // 對巨集目錄的'/'字元新增反斜線''
  326. $path = preg_replace("/(. ?)/*$/", "\1/", $path);
  327. //取得目錄檔案清單
  328. $filelist = $ this->filelist($path);
  329. if($filelist !== FALSE AND count($filelist) > 0) {
  330. foreach($filelist as $item) {
  331. //如果我們無法刪除,那麼就可能是資料夾
  332. //所以我們呼叫delete_dir()
  333. if( ! @delete_file($item)) {
  334. $this-> ;delete_dir($item);
  335. }
  336. }
  337. }
  338. //資料夾刪除(空資料夾)
  339. $result = @ftp_rmdir($this->conn_id, $path );
  340. if($result = == FALSE) {
  341. if($this->debug === TRUE) {
  342. $this->_error("ftp_unable_to_delete_dir:dir[".$路徑。"]");
  343. }
  344. 回傳FALSE;
  345. }
  346. 回傳TRUE;
  347. }
  348. /**
  349. * 修改檔案權限
  350. *
  351. * @access public
  352. * @param string 目錄識別(ftp)
  353. * @return boolean
  354. */
  355. public function chmod($路徑, $perm) {
  356. if( ! $this->_isconn()) {
  357. return FALSE;
  358. }
  359. //只有在PHP5才定義了修改權限的函數(ftp)
  360. if( ! function_exists('ftp_chmod' ) ) {
  361. if($this->debug === TRUE) {
  362. $this->_error("ftp_unable_to_chmod(function)");
  363. }
  364. return FALSE;
  365. }
  366. }
  367. return FALSE;
  368. }
  369. }
  370. return FALSE;
  371. }
  372. $result = @ftp_chmod($this->conn_id, $perm, $path);
  373. if($result === FALSE) {
  374. if($this->debug = == TRUE) {
  375. $this->_error("ftp_unable_to_chmod:path[".$path."]-chmod[".$perm."]");
  376. }
  377. return FALSE;
  378. }
  379. return TRUE;
  380. }
  381. /**
  382. * 取得目錄檔案清單
  383. *
  384. * @access public
  385. * @param string 目錄識別(ftp)
  386. * @return array
  387. */
  388. public function filelist($path = '.') {
  389. if( ! $this-> ;_isconn()) {
  390. return FALSE;
  391. }
  392. return ftp_nlist($this->conn_id, $path);
  393. }
  394. /**
  395. * 關閉FTP
  396. *
  397. * @access public
  398. * @return boolean
  399. */
  400. public function close() { if( ! $this->_isconn()) { return FALSE; } return @ftp_close($this->conn_id); }
  401. /**
  402. * FTP 멤버 변수 초기화
  403. *
  404. * @access private
  405. * @param 배열 구성 배열
  406. * @return void
  407. */
  408. 비공개 함수 _init($config = array()) {
  409. foreach($config as $key => $val) {
  410. if(isset( $this->$key)) {
  411. $this->$key = $val;
  412. }
  413. }
  414. //特殊字符过滤
  415. $this->hostname = preg_replace('|. ?://|','',$this->hostname);
  416. }
  417. /**
  418. * FTP登陆
  419. *
  420. * @access private
  421. * @return boolean
  422. */
  423. 비공개 함수 _login() {
  424. return @ftp_login($this->conn_id, $this->username, $this->password);
  425. }
  426. /**
  427. * 문서 con_id
  428. *
  429. * @access private
  430. * @return boolean
  431. */
  432. 개인 함수 _isconn() {
  433. if( !is_resource($this->conn_id)) {
  434. if($this->debug === TRUE) {
  435. $this->_error("ftp_no_connection");
  436. }
  437. FALSE 반환;
  438. }
  439. TRUE 반환;
  440. }
  441. /**
  442. * 파일 이름에서 접미사 확장자를 가져옵니다.
  443. *
  444. * @access private
  445. * @param 문자열 디렉터리 식별자
  446. * @return 문자열
  447. */
  448. 비공개 함수 _getext($filename) {
  449. if( FALSE === strpos($filename, '.')) {
  450. return 'txt';
  451. }
  452. $extarr =Explode('.', $filename);
  453. return end($ extarr);
  454. }
  455. /**
  456. * 접미사 확장자 ASCII 또는 바이너리에서 FTP 전송 모드 정의
  457. *
  458. * @access private
  459. * @param 문자열 접미사 확장
  460. * @return 문자열
  461. */
  462. 비공개 함수 _settype($ext) {
  463. $text_type = array (
  464. 'txt',
  465. 'text' ,
  466. 'php',
  467. 'phps',
  468. 'php4',
  469. 'js',
  470. 'css',
  471. 'htm',
  472. 'html',
  473. 'phtml',
  474. 'shtml',
  475. 'log',
  476. 'xml'
  477. );
  478. return (in_array($ext, $text_type)) ? 'ascii' : 'binary';
  479. }
  480. /**
  481. * 오류 로깅
  482. *
  483. * @access prvate
  484. * @return boolean
  485. */
  486. 개인 함수 _error($msg) {
  487. 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);
  488. }
  489. }
  490. /*파일 끝 ftp.php*/
  491. /*위치 /Apache Group/htdocs/ftp.php*/
复system代码

上传文件, ftp, php


本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

在PHP API中說明JSON Web令牌(JWT)及其用例。 在PHP API中說明JSON Web令牌(JWT)及其用例。 Apr 05, 2025 am 12:04 AM

JWT是一種基於JSON的開放標準,用於在各方之間安全地傳輸信息,主要用於身份驗證和信息交換。 1.JWT由Header、Payload和Signature三部分組成。 2.JWT的工作原理包括生成JWT、驗證JWT和解析Payload三個步驟。 3.在PHP中使用JWT進行身份驗證時,可以生成和驗證JWT,並在高級用法中包含用戶角色和權限信息。 4.常見錯誤包括簽名驗證失敗、令牌過期和Payload過大,調試技巧包括使用調試工具和日誌記錄。 5.性能優化和最佳實踐包括使用合適的簽名算法、合理設置有效期、

會話如何劫持工作,如何在PHP中減輕它? 會話如何劫持工作,如何在PHP中減輕它? Apr 06, 2025 am 12:02 AM

會話劫持可以通過以下步驟實現:1.獲取會話ID,2.使用會話ID,3.保持會話活躍。在PHP中防範會話劫持的方法包括:1.使用session_regenerate_id()函數重新生成會話ID,2.通過數據庫存儲會話數據,3.確保所有會話數據通過HTTPS傳輸。

描述紮實的原則及其如何應用於PHP的開發。 描述紮實的原則及其如何應用於PHP的開發。 Apr 03, 2025 am 12:04 AM

SOLID原則在PHP開發中的應用包括:1.單一職責原則(SRP):每個類只負責一個功能。 2.開閉原則(OCP):通過擴展而非修改實現變化。 3.里氏替換原則(LSP):子類可替換基類而不影響程序正確性。 4.接口隔離原則(ISP):使用細粒度接口避免依賴不使用的方法。 5.依賴倒置原則(DIP):高低層次模塊都依賴於抽象,通過依賴注入實現。

PHP 8.1中的枚舉(枚舉)是什麼? PHP 8.1中的枚舉(枚舉)是什麼? Apr 03, 2025 am 12:05 AM

PHP8.1中的枚舉功能通過定義命名常量增強了代碼的清晰度和類型安全性。 1)枚舉可以是整數、字符串或對象,提高了代碼可讀性和類型安全性。 2)枚舉基於類,支持面向對象特性,如遍歷和反射。 3)枚舉可用於比較和賦值,確保類型安全。 4)枚舉支持添加方法,實現複雜邏輯。 5)嚴格類型檢查和錯誤處理可避免常見錯誤。 6)枚舉減少魔法值,提升可維護性,但需注意性能優化。

在PHPStorm中如何進行CLI模式的調試? 在PHPStorm中如何進行CLI模式的調試? Apr 01, 2025 pm 02:57 PM

在PHPStorm中如何進行CLI模式的調試?在使用PHPStorm進行開發時,有時我們需要在命令行界面(CLI)模式下調試PHP�...

如何在系統重啟後自動設置unixsocket的權限? 如何在系統重啟後自動設置unixsocket的權限? Mar 31, 2025 pm 11:54 PM

如何在系統重啟後自動設置unixsocket的權限每次系統重啟後,我們都需要執行以下命令來修改unixsocket的權限:sudo...

如何用PHP的cURL庫發送包含JSON數據的POST請求? 如何用PHP的cURL庫發送包含JSON數據的POST請求? Apr 01, 2025 pm 03:12 PM

使用PHP的cURL庫發送JSON數據在PHP開發中,經常需要與外部API進行交互,其中一種常見的方式是使用cURL庫發送POST�...

See all articles