


PHP operation FTP class (upload, download, move, create, etc.), phpftp_PHP tutorial
Jul 12, 2016 am 08:55 AMPHP operates FTP class (upload, download, move, create, etc.), phpftp
This article provides a detailed introduction to PHP operating FTP class, php implements FTP upload, FTP download, FTP Mobile, FTP creation, etc., for your reference, the specific content is as follows
1. Use PHP to operate FTP-usage
<?php // 聯(lián)接FTP服務(wù)器 $conn = ftp_connect(ftp.server.com); // 使用username和password登錄 ftp_login($conn, “john”, “doe”); // 獲取遠端系統(tǒng)類型 ftp_systype($conn); // 列示文件 $filelist = ftp_nlist($conn, “.”); // 下載文件 ftp_get($conn, “data.zip”, “data.zip”, FTP_BINARY); // 關(guān)閉聯(lián)接 ftp_quit($conn); //初結(jié)化一個FTP聯(lián)接,PHP提供了ftp_connect()這個函數(shù),它使用主機名稱和端口作為參數(shù)。在上面的例子里,主機名字為 “ftp.server.com”;如果端口沒指定,PHP將會使用“21”作為缺省端口來建立聯(lián)接。 //聯(lián)接成功后ftp_connect()傳回一個handle句柄;這個handle將被以后使用的FTP函數(shù)使用。 $conn = ftp_connect(ftp.server.com); //一旦建立聯(lián)接,使用ftp_login()發(fā)送一個用戶名稱和用戶密碼。你可以看到,這個函數(shù)ftp_login()使用了 ftp_connect()函數(shù)傳來的handle,以確定用戶名和密碼能被提交到正確的服務(wù)器。 ftp_login($conn, “john”, “doe”); // close connection ftp_quit($conn); //登錄了FTP服務(wù)器,PHP提供了一些函數(shù),它們能獲取一些關(guān)于系統(tǒng)和文件以及目錄的信息。 ftp_pwd() //獲取當(dāng)前所在的目錄 $here = ftp_pwd($conn); //獲取服務(wù)器端系統(tǒng)信息ftp_systype() $server_os = ftp_systype($conn); //被動模式(PASV)的開關(guān),打開或關(guān)閉PASV(1表示開) ftp_pasv($conn, 1); //進入目錄中用ftp_chdir()函數(shù),它接受一個目錄名作為參數(shù)。 ftp_chdir($conn, “public_html”); //回到所在的目錄父目錄用ftp_cdup()實現(xiàn) ftp_cdup($conn); //建立或移動一個目錄,這要使用ftp_mkdir()和ftp_rmdir()函數(shù);注意:ftp_mkdir()建立成功的話,就會返回新建立的目錄名。 ftp_mkdir($conn, “test”); ftp_rmdir($conn, “test”); //上傳文件,ftp_put()函數(shù)能很好的勝任,它需要你指定一個本地文件名,上傳后的文件名以及傳輸?shù)念愋?。比方說:如果你想上傳 “abc.txt”這個文件,上傳后命名為“xyz.txt”,命令應(yīng)該是這樣: ftp_put($conn, “xyz.txt”, “abc.txt”, FTP_ASCII); //下載文件:PHP所提供的函數(shù)是ftp_get(),它也需要一個服務(wù)器上文件名,下載后的文件名,以及傳輸類型作為參數(shù),例如:服務(wù)器端文件為his.zip,你想下載至本地機,并命名為hers.zip,命令如下: ftp_get($conn, “hers.zip”, “his.zip”, FTP_BINARY); //PHP提供兩種方法:一種是簡單列示文件名和目錄,另一種就是詳細的列示文件的大小,權(quán)限,創(chuàng)立時間等信息。 //第一種使用ftp_nlist()函數(shù),第二種用ftp_rawlist().兩種函數(shù)都需要一個目錄名做為參數(shù),都返回目錄列做為一個數(shù)組,數(shù)組的每一個元素相當(dāng)于列表的一行。 $filelist = ftp_nlist($conn, “.”); //函數(shù)ftp_size(),它返回你所指定的文件的大小,使用BITES作為單位。要指出的是,如果它返回的是 “-1”的話,意味著這是一個目錄 $filelist = ftp_size($conn, “data.zip”); ?>
2. FTP upload class (ftp.php)
<?php /******************************************** * MODULE:FTP類 *******************************************/ class ftp { public $off; // 返回操作狀態(tài)(成功/失敗) public $conn_id; // FTP連接 /** * 方法:FTP連接 * @FTP_HOST -- FTP主機 * @FTP_PORT -- 端口 * @FTP_USER -- 用戶名 * @FTP_PASS -- 密碼 */ function __construct($FTP_HOST,$FTP_PORT,$FTP_USER,$FTP_PASS) { $this->conn_id = @ftp_connect($FTP_HOST,$FTP_PORT) or die("FTP服務(wù)器連接失敗"); @ftp_login($this->conn_id,$FTP_USER,$FTP_PASS) or die("FTP服務(wù)器登陸失敗"); @ftp_pasv($this->conn_id,1); // 打開被動模擬 } /** * 方法:上傳文件 * @path -- 本地路徑 * @newpath -- 上傳路徑 * @type -- 若目標目錄不存在則新建 */ function up_file($path,$newpath,$type=true) { if($type) $this->dir_mkdirs($newpath); $this->off = @ftp_put($this->conn_id,$newpath,$path,FTP_BINARY); if(!$this->off) echo "文件上傳失敗,請檢查權(quán)限及路徑是否正確!"; } /** * 方法:移動文件 * @path -- 原路徑 * @newpath -- 新路徑 * @type -- 若目標目錄不存在則新建 */ function move_file($path,$newpath,$type=true) { if($type) $this->dir_mkdirs($newpath); $this->off = @ftp_rename($this->conn_id,$path,$newpath); if(!$this->off) echo "文件移動失敗,請檢查權(quán)限及原路徑是否正確!"; } /** * 方法:復(fù)制文件 * 說明:由于FTP無復(fù)制命令,本方法變通操作為:下載后再上傳到新的路徑 * @path -- 原路徑 * @newpath -- 新路徑 * @type -- 若目標目錄不存在則新建 */ function copy_file($path,$newpath,$type=true) { $downpath = "c:/tmp.dat"; $this->off = @ftp_get($this->conn_id,$downpath,$path,FTP_BINARY);// 下載 if(!$this->off) echo "文件復(fù)制失敗,請檢查權(quán)限及原路徑是否正確!"; $this->up_file($downpath,$newpath,$type); } /** * 方法:刪除文件 * @path -- 路徑 */ function del_file($path) { $this->off = @ftp_delete($this->conn_id,$path); if(!$this->off) echo "文件刪除失敗,請檢查權(quán)限及路徑是否正確!"; } /** * 方法:生成目錄 * @path -- 路徑 */ function dir_mkdirs($path) { $path_arr = explode('/',$path); // 取目錄數(shù)組 $file_name = array_pop($path_arr); // 彈出文件名 $path_div = count($path_arr); // 取層數(shù) foreach($path_arr as $val) // 創(chuàng)建目錄 { if(@ftp_chdir($this->conn_id,$val) == FALSE) { $tmp = @ftp_mkdir($this->conn_id,$val); if($tmp == FALSE) { echo "目錄創(chuàng)建失敗,請檢查權(quán)限及路徑是否正確!"; exit; } @ftp_chdir($this->conn_id,$val); } } for($i=1;$i<=$path_div;$i++) // 回退到根 { @ftp_cdup($this->conn_id); } } /** * 方法:關(guān)閉FTP連接 */ function close() { @ftp_close($this->conn_id); } } // class class_ftp end
/************************************** 測試 *********************************** $ftp = new ftp('222.13.67.42',21,'hlj','123456'); // 打開FTP連接 $ftp->up_file('aa.wav','test/13548957217/bb.wav'); // 上傳文件 //$ftp->move_file('aaa/aaa.php','aaa.php'); // 移動文件 //$ftp->copy_file('aaa.php','aaa/aaa.php'); // 復(fù)制文件 //$ftp->del_file('aaa.php'); // 刪除文件 $ftp->close(); // 關(guān)閉FTP連接 //******************************************************************************/
3. PHP uses FTP function to create a directory
<?php // create directory through FTP connection function FtpMkdir($path, $newDir) { $server='ftp.yourserver.com'; // ftp server $connection = ftp_connect($server); // connection // login to ftp server $user = "me"; $pass = "password"; $result = ftp_login($connection, $user, $pass); // check if connection was made if ((!$connection) || (!$result)) { return false; exit(); } else { ftp_chdir($connection, $path); // go to destination dir if(ftp_mkdir($connection,$newDir)) { // create directory return $newDir; } else { return false; } ftp_close($conn_id); // close connection } } ?>
The above is the entire content of this article. I hope it will be helpful to everyone in learning PHP programming.
Articles you may be interested in:
- Code to implement online management of FTP users using PHP
- bplaced Germany can bind rice 2G to support FTP free PHP space
- php program to download file tree from ftp server to local computer
- Connect ftp under php to upload, download and delete files example code
- php ftp file upload function (basic version)
- No need to recompile php to add ftp extension solution
- In-depth explanation of PHP FTP class
- win2008 r2 server environment configuration (FTP/ASP/ASP.Net/ PHP)
- PHP FTP operation code (upload, copy, move, delete files/create directory)
- PHP implementation of ftp upload file example

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas
