PHP的FTP學習

發表于:2007-07-14來源:作者:點擊數: 標簽:
我們是一群PHP的忠實FANS,我們因各種不同的原因使用它-WEB站點的 開發 ,畫圖, 數據庫 的聯接等 -我們發現,它非常的友好,強大而且易于使用…… 你可能已經看到PHP是怎樣被用于創建GIF和JPEG圖像,從數據庫中動態的獲取信息等等,但這只是冰山的一角---最


我們是一群PHP的忠實FANS,我們因各種不同的原因使用它-WEB站點的開發,畫圖,數據庫的聯接等 -我們發現,它非常的友好,強大而且易于使用……
你可能已經看到PHP是怎樣被用于創建GIF和JPEG圖像,從數據庫中動態的獲取信息等等,但這只是冰山的一角---最新版本的PHP擁有著強大的文件傳輸功能。
在這篇教程里,我將向你展示FTP怎樣通過HTTP和FTP聯接來傳輸文件,同時也會有一些簡單的程序代碼,跟我來吧!

首先,你應該知道PHP是通過HTTP和FTP聯接來傳輸文件的。通過HTTP上傳文件早在PHP3中就已經出現,現在,新的FTP函數已經在新的PHP版本中出現了!
開始之前,你需要確信你的PHP支持FTP,你可以通過以下代碼查知:

--------------------------------------------------------------------------------
<?

phpinfo();

?>
--------------------------------------------------------------------------------
檢查輸出結果,有一“Additional Modules”區,這里列示了你的PHP支持的模塊;如果你沒發現FTP模塊,你最好重新安裝PHP,并添加FTP支持!

先讓我們來看看一個典型的FTP任務是怎樣完成的吧!
--------------------------------------------------------------------------------
$ ftp ftp.server.com
Connected to ftp.server.com
220 server.com FTP server ready.
Name (server:john): john
331 Password required for john.
Password:
230 User john logged in.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> ls
200 PORT command suclearcase/" target="_blank" >ccessful.
150 Opening ASCII mode data connection for /bin/ls.
drwxr-xr-x 5 john users 3072 Nov 2 11:03 .
drwxr-xr-x 88 root root 2048 Nov 1 23:26 ..
drwxr--r-- 2 john users 1024 Oct 5 13:26 bin
drwx--x--x 8 john users 1024 Nov 2 10:59 public_html
drwxr--r-- 4 john users 1024 Nov 2 11:26 tmp
-rw-r--r-- 1 john users 2941465 Oct 9 17:21 data.zip
226 Transfer complete.
ftp> bin
200 Type set to I.
ftp> get data.zip
local: data.zip remote: data.zip
200 PORT command successful.
150 Opening BINARY mode data connection for data.zip(2941465 bytes).
226 Transfer complete.
ftp> bye
221 Goodbye.
--------------------------------------------------------------------------------
你可以看到,進程明顯被分為幾段:聯接(與FTP服務器建立聯接)、驗證(確定用戶是否有權力進入系統)、傳輸(這里包括列目錄,上傳或下載文件)、取消聯接。

使用PHP來FTP的步驟
建立一個PHP的FTP聯接必須遵守以下基本步驟:打開一個聯接 - 發出認證信息 - 使用PHP函數操縱目錄和傳輸文件。
以下具體實現:
--------------------------------------------------------------------------------
<?

// 聯接FTP服務器
$conn = ftp_connect("ftp.server.com");

// 使用username和password登錄
ftp_login($conn, "john", "doe");

// 獲取遠端系統類型
ftp_systype($conn);

// 列示文件
$filelist = ftp_nlist($conn, ".");

// 下載文件
ftp_get($conn, "data.zip", "data.zip", FTP_BINARY);

// 關閉聯接
ftp_quit($conn);

?>
--------------------------------------------------------------------------------
讓我們一步步的來:
為了初結化一個FTP聯接,PHP提供了ftp_connect()這個函數,它使用主機名稱和端口作為參數。在上面的例子里,主機名字為“ftp.server.com”;如果端口沒指定,PHP將會使用“21”作為缺省端口來建立聯接。
聯接成功后ftp_connect()傳回一個handle句柄;這個handle將被以后使用的FTP函數使用。
--------------------------------------------------------------------------------
<?

// connect to FTP server
$conn = ftp_connect("ftp.server.com");

?>
--------------------------------------------------------------------------------
一旦建立聯接,使用ftp_login()發送一個用戶名稱和用戶密碼。你可以看到,這個函數ftp_login()使用了ftp_connect()函數傳來的handle,以確定用戶名和密碼能被提交到正確的服務器。
--------------------------------------------------------------------------------
<?

// log in with username and password
ftp_login($conn, "john", "doe");

?>
--------------------------------------------------------------------------------
這時,你就能夠做你想做的事情了,具體在下一部分講:

做完你想做的事后,千萬要記住使用ftp_quit()函數關閉你的FTP聯接

--------------------------------------------------------------------------------
<?

// close connection
ftp_quit($conn);

?>
--------------------------------------------------------------------------------
登錄了FTP服務器,PHP提供了一些函數,它們能獲取一些關于系統和文件以及目錄的信息。

ftp_pwd()
如果你想知道你當前所在的目錄時,你就要用到這個函數了。
--------------------------------------------------------------------------------
<?

// get current location
$here = ftp_pwd($conn);

?>
--------------------------------------------------------------------------------
萬一你需要知道服務器端運行的是什么系統呢?
ftp_systype()正好提供給你這方面的信息。
--------------------------------------------------------------------------------
<?

// get system type
$server_os = ftp_systype($conn);

?>
--------------------------------------------------------------------------------
關于被動模式(PASV)的開關,PHP也提供了這樣一個函數,它能打開或關閉PASV(1表示開)
--------------------------------------------------------------------------------
<?

// turn PASV on
ftp_pasv($conn, 1);

?>
--------------------------------------------------------------------------------

現在,你已經知道你在“哪里”和“誰”跟你在一起了吧,現在我們開始在目錄中逛逛--實現這一功能的是ftp_chdir()函數,它接受一個目錄名作為參數。
--------------------------------------------------------------------------------
<?

// change directory to "public_html"
ftp_chdir($conn, "public_html");

?>
--------------------------------------------------------------------------------
如果你想回到你剛才所在的目錄(父目錄),ftp_cdup()能幫你實現你的愿望,這個函數能回到上一級目錄。
--------------------------------------------------------------------------------
<?

// go up one level in the directory tree
ftp_cdup($conn);

?>
--------------------------------------------------------------------------------
你也能夠建立或移動一個目錄,這要使用ftp_mkdir()和ftp_rmdir()函數;注意:ftp_mkdir()建立成功的話,就會返回新建立的目錄名。
--------------------------------------------------------------------------------
<?

// make the directory "test"
ftp_mkdir($conn, "test");

// remove the directory "test"
ftp_rmdir($conn, "test");

?>
--------------------------------------------------------------------------------
建立一個FTP的目錄通常是傳輸文件--- 那么就讓我們開始吧!

先是上傳文件,ftp_put()函數能很好的勝任這一職責,它需要你指定一個本地文件名,上傳后的文件名以及傳輸的類型。比方說:如果你想上傳“abc.txt”這個文件,上傳后命名為“xyz.txt”,命令應該是這樣:
--------------------------------------------------------------------------------
<?

// upload
ftp_put($conn, "xyz.txt", "abc.txt", FTP_ASCII);

?>
--------------------------------------------------------------------------------
下載文件:
PHP所提供的函數是ftp_get(),它也需要一個服務器上文件名,下載后的文件名,以及傳輸類型作為參數,例如:服務器端文件為his.zip,你想下載至本地機,并命名為hers.zip,命令如下:
--------------------------------------------------------------------------------
<?

// download
ftp_get($conn, "hers.zip", "his.zip", FTP_BINARY);

?>
--------------------------------------------------------------------------------
PHP定義了兩種模式作為傳輸模式 FTP_BINARY 和 FTP_ASCII ,這兩種模式的使用請看上兩例,至于其詳細解釋,本文也不多說了,具體請參看相關書籍。

 

我該怎樣列示文件呢?(用DIR? :) )
PHP提供兩種方法:一種是簡單列示文件名和目錄,另一種就是詳細的列示文件的大小,權限,創立時間等信息。
第一種使用ftp_nlist()函數,第二種用ftp_rawlist().兩種函數都需要一個目錄名做為參數,都返回目錄列做為一個數組,數組的每一個元素相當于列表的一行。
--------------------------------------------------------------------------------
<?

// obtain file listing
$filelist = ftp_nlist($conn, ".");

?>
--------------------------------------------------------------------------------
你一定想知道文件的大小吧!別急,這里有一個非常容易的函數ftp_size(),它返回你所指定的文件的大小,使用BITES作為單位。要指出的是,如果它返回的是 “-1”的話,意味著這是一個目錄,在隨后的例子中,你將會看到這一功能的應用。
--------------------------------------------------------------------------------
<?

// obtain file size of file "data.zip"
$filelist = ftp_size($conn, "data.zip");

?>

現在,我們已經接觸了PHP關于FTP的大量函數,但這僅僅只是函數,離我們的目標還遠遠不夠,要顯示出這些函數的真正力量,我們應該建立一個程序,這個程序能以WEB方式上傳,下載文件---這就是我們將要做的!

在我們進入代碼前,我想要告訴大家的是,這個例子僅僅只是為了向大家解釋PHP的各種FTP函數的使用,很多方面還不夠完善,比如說,錯誤分析等,至于你想應用到你自己的程序中,你應該進行一些修改!

程序包括以下幾個文件:
index.html - 登錄文件

actions.php - 程序必需的FTP代碼

include.php - 程序主界面,它顯示文件列表和控制按鈕。

讓我們從 "index.html"開始吧:
--------------------------------------------------------------------------------
<table border=0 align=center>
<form action="actions.php" method=post>
<input type=hidden name=action value=CWD>
<tr>
<td>
Server
</td>
<td>
<input type=text name=server>
</td>
</tr>

<tr>
<td>
User
</td>
<td>
<input type=text name=username>
</td>
</tr>

<tr>
<td>
Password
</td>
<td>
<input type=password name=password>
</td>
</tr>

<tr>
<td colspan=2 align=center>
<input type="submit" value="Beam Me Up, Scotty!">
</td>
</tr>

</form>
</table>
--------------------------------------------------------------------------------
這是一個登錄表單,有一個服務器名稱、用戶名、密碼,輸入框。輸入的變量將會被存到$server, $username 和 $password 變量中,表單提交后,調用actions.php,它將初始化FTP聯接。

注意那個“hidden” 它傳給action.php一個變量$action ,值為CWD。

這是action.php文件的源碼:
--------------------------------------------------------------------------------
<html>
<head>
<basefont face=Arial>
</head>
<body>

<!-- the include.php interface will be inserted into this page -->

<?

//檢查表單傳來的數據,不全則報錯,要想程序完善的話,這里應該有更全的輸入檢測功能
if (!$server || !$username || !$password)
{
echo "提交數據不全!";
}
else
{
// keep reading
}

?>

</body>
</html>
--------------------------------------------------------------------------------

接下來是變量 "actions". 程序允許以下的action:

"action=CWD"

改變工作目錄

"action=Delete"

刪除指定文件

"action=Download"

下載指定文件

"action=Upload"

上傳指定文件

如果你仔細檢查文件include.php,在里面包括一個HTML界面,你將會看到,它包括許多表單,每一個指向一個特定的功能,每一個表單包含一個field(通常隱藏) ,當表單提交,相應的功能將被執行。

例如:按下“刪除”,"action=Delete"就被傳送給"actions.php"

為了操作這四個功能,actions.php中代碼如下:
--------------------------------------------------------------------------------
<?
// action: 改變目錄
if ($action == "CWD")
{
// 具體代碼
}

// action: 刪除文件
else if ($action == "Delete")
{
// 具體代碼
}
// action: 下載文件
else if ($action == "Download")
{
// 具體代碼
}
// action: 上傳文件
else if ($action == "Upload")
{
// 具體代碼
}

?>
--------------------------------------------------------------------------------
以上的具體代碼將會實現指定的功能,并退出循環,它們都包含以下步驟:

--------------------------------------------------------------------------------
通過定制的函數聯接并登錄FTP服務器
connect();

轉向適當的目錄

執行選擇的功能

刷新列表,以察看改變的結果

通過include("include.php"),顯示文件列表和控制按鈕

關閉聯接
--------------------------------------------------------------------------------
注意:
以下功能支持多文件操作- 即 "action=Delete" 和 "action=Download" 它們使用FOR循環來實現。
變量$cdir 和 $here 將在每一階段實時更新。

現在終于到了我們的第三個文件,include.php 它為程序建立起一個用戶界面。

"include.php" 包含三個表單,一些PHP代碼獲取當前的目錄列表并將它們存入三個變量
$files (包括當前目錄下的文件),
$file_sizes (相應的文件大小),
and $dirs (包含子目錄名)

第一個表單使用$dirs 產生一個下拉式目錄列表,對應于“action=CWD”。

第二個表單使用$files $file_sizes創建一個可用的文件列表,每一個文件使用一個checkbox。這個表單的action對應于"action=Delete" and "action=Download"

第三個表單用來上傳一個文件到FTP站點,如下:
--------------------------------------------------------------------------------
<form enctype="multipart/form-data" action=actions.php4 method=post>
...
<input type=file name=upfile>
...
</form>
--------------------------------------------------------------------------------
當PHP以這種方式接收到一個文件名,一些變量就產生了,這些變量指定文件的大小,一個臨時的文件名以及文件的類型,最初的文件名存在$upfile_name,一旦上傳后文件名便存入$upfile中(這個變量是由PHP自己創建的)
通過這些信息,我們就可以創建以下的語句了:
--------------------------------------------------------------------------------
ftp_put($result, $upfile_name, $upfile, FTP_BINARY);
--------------------------------------------------------------------------------
以下是代碼列表:
--------------------------------------------------------------------------------
<!-- code for index.html begins here -->
<html>
<head>
<basefont face=arial>
</head>

<body>

<table border=0 align=center>
<form action="actions.php" method=post>
<input type=hidden name=action value=CWD>
<tr>
<td>
Server
</td>
<td>
<input type=text name=server>
</td>
</tr>

<tr>
<td>
User
</td>
<td>
<input type=text name=username>
</td>
</tr>

<tr>
<td>
Password
</td>
<td>
<input type=password name=password>
</td>
</tr>

<tr>
<td colspan=2 align=center>
<input type="submit" value="Beam Me Up, Scotty!">
</td>
</tr>

</form>
</table>

</body>
</html>

<!-- code for index.html ends here -->
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
<!-- code for actions.php begins here -->

<html>
<head>
<basefont face=Arial>
</head>
<body>

<?
/*
--------------------------------------------------------------------------------
DISCLAIMER:

This is use-at-your-own-risk code.

It is meant only for illustrative purposes and is not meant for production environments. No warranties of any kind are provided to the user.

You have been warned!

All code copyright Melonfire, 2000. Visit us at http://www.melonfire.com
--------------------------------------------------------------------------------
*/

// function to connect to FTP server
function connect()
{
global $server, $username, $password;
$conn = ftp_connect($server);
ftp_login($conn, $username, $password);
return $conn;
}

// main program begins

// check for valid form entries else print error
if (!$server || !$username || !$password)
{
echo "Form data incomplete!";
}
else
{

// connect
$result = connect();

// action: change directory
if ($action == "CWD")
{

// at initial stage $rdir does not exist
// so assume default directory
if (!$rdir)
{
$path = ".";
}
// get current location $cdir and add it to requested directory $rdir
else
{
$path = $cdir . "/" . $rdir;
}

// change to requested directory
ftp_chdir($result, $path);

}

// action: delete file(s)
else if ($action == "Delete")
{

ftp_chdir($result, $cdir);

// loop through selected files and delete
for ($x=0; $x<sizeof($dfile); $x++)
{
ftp_delete($result, $cdir . "/" . $dfile[$x]);
}

}
// action: download files
else if ($action == "Download")
{

ftp_chdir($result, $cdir);

// download selected files
// IMPORTANT: you should specify a different download location here!!
for ($x=0; $x<sizeof($dfile); $x++)
{
ftp_get($result, $dfile[$x], $dfile[$x], FTP_BINARY);
}

}
// action: upload file
else if ($action == "Upload")
{

ftp_chdir($result, $cdir);

// put file

/*
a better idea would be to use
$res_code = ftp_put($result, $HTTP_POST_FILES["upfile"]["name"],
$HTTP_POST_FILES["upfile"]["tmp_name"], FTP_BINARY);
as it offers greater security
*/
$res_code = ftp_put($result, $upfile_name, $upfile, FTP_BINARY);

// check status and display
if ($res_code == 1)
{
$status = "Upload successful!";
}
else
{
$status = "Upload error!";
}

}

// create file list
$filelist = ftp_nlist($result, ".");

// and display interface
include("include.php");

// close connection
ftp_quit($result);

}
?>

</body>
</html>

<!-- code for actions.php ends here -->
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
<!-- code for include.php begins here -->

<?

// get current location
$here = ftp_pwd($result);

/*
since ftp_size() is quite slow, especially when working
on an array containing all the files in a directory,
this section performs an ftp_size() on all the files in the current
directory and creates three arrays.
*/

// array for files
$files = Array();

// array for directories
$dirs = Array();

// array for file sizes
$file_sizes = Array();

// counters
$file_list_counter = 0;
$dir_list_counter = 0;

// check each element of $filelist
for ($x=0; $x<sizeof($filelist); $x++)
{
if (ftp_size($result, $filelist[$x]) != -1)
{
// create arrays
$files[$file_list_counter] = $filelist[$x];
$file_sizes[$file_list_counter] = ftp_size($result, $filelist[$x]);
$file_list_counter++;
}
else
{
$dir_list[$dir_list_counter] = $filelist[$x];
$dir_list_counter++;
}
}

?>

<!-- header - where am I? -->
<center>
You are currently working in <b><? echo $here; ?></b>
<br>
<!-- status message for upload function -->
<? echo $status; ?>
</center>
<hr>
<p>
<!-- directory listing in drop-down list -->
Available directories:
<form action=actions.php method=post>

<!-- these values are passed hidden every time -->
<!-- a more optimal solution might be to place these in session
variables -->
<input type=hidden name=username value=<? echo $username; ?>>
<input type=hidden name=password value=<? echo $password; ?>>
<input type=hidden name=server value=<? echo $server; ?>>
<input type=hidden name=cdir value=<? echo $here; ?>>

<!-- action to take when THIS form is submitted -->
<input type=hidden name=action value=CWD>

<!-- dir listing begins; first item is for parent dir -->
<select name=rdir>
<option value=".."><parent directory></option>

<?

for ($x=0; $x<sizeof($dir_list); $x++)
{
echo "<option value=" . $dir_list[$x] . ">" . $dir_list[$x] . "</option>";

}
?>

</select>
<input type=submit value=Go>
</form>

<hr>

<!-- file listing begins -->

Available files:
<form action=actions.php method=post>

<!-- these values are passed hidden every time -->
<input type=hidden name=server value=<? echo $server; ?>>
<input type=hidden name=username value=<? echo $username; ?>>
<input type=hidden name=password value=<? echo $password; ?>>
<input type=hidden name=cdir value=<? echo $here; ?>>

<table border=0 width=100%>

<?

// display file listing with checkboxes and sizes
for ($y=0; $y<sizeof($files); $y++)
{
echo "<tr><td><input type=checkbox name=dfile[] value=" . $files[$y] .
">". $files[$y] . " <i>(" . $file_sizes[$y] . " bytes)</i><td>";
}

?>
</table>

<!-- actions for this form -->
<center>
<input type=submit name=action value=Delete>
<input type=submit name=action value=Download>
</center>
</form>
<p>

<hr>

<!-- file upload form -->
File upload:
<form enctype="multipart/form-data" action=actions.php method=post>

<!-- these values are passed hidden every time -->
<input type=hidden name=username value=<? echo $username; ?>>
<input type=hidden name=password value=<? echo $password; ?>>
<input type=hidden name=server value=<? echo $server; ?>>
<input type=hidden name=cdir value=<? echo $here; ?>>

<table>
<tr>
<td>
<!-- file selection box -->
<input type=file name=upfile>
</td>
</tr>
<tr>
<td>
<!-- action for this form -->
<input type=submit name=action value=Upload>
</td>
</tr>
</table>
</form>

<!-- code for include.php ends here -->

原文轉自:http://www.anti-gravitydesign.com

国产97人人超碰caoprom_尤物国产在线一区手机播放_精品国产一区二区三_色天使久久综合给合久久97