Php ftp Learning (1) [transfer from Osso]

Source: Internet
Author: User
Tags ftp connection


By Vikram Vaswani
Melonfire
November 07,200 0
We are a loyal fans of a group of PHP, and we use it for various reasons-Web site development, drawing, database connection, etc.-we found it very friendly, powerful and easy to use ......
You may have seen how PHP is used to create GIF and JPEG images and Dynamically Retrieve Information from the database, but this is only the tip of the iceberg-the latest version of PHP has a powerful file transfer function.
In this tutorial, I will show you how ftp transfers files through HTTP and FTP connections, and some simple Program Code Come with me!

First, you should know that PHP transfers files through HTTP and FTP connections. Uploading files via HTTP has already appeared in php3, and now the new FTP function has appeared in the New PHP version!
Before you start, make sure that your PHP supports FTP. You can check the following code:

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

Phpinfo ();

?>
--------------------------------------------------------------------------------
Check the output result. There is an "additional modules" area, which lists the modules supported by your php. If you do not find the FTP module, you 'd better reinstall PHP and add FTP support!

Let's take a look at how a typical FTP task is completed!
--------------------------------------------------------------------------------
$ 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 successful.
150 opening ASCII mode data connection for/bin/LS.
Drwxr-XR-x 5 John users 3072 Nov 2.
Drwxr-XR-x 88 Root 2048 Nov 1 ..
Drwxr -- r -- 2 John users 1024 Oct 5 Bin
Drwx -- X -- x 8 John users 1024 Nov 2 public_html
Drwxr -- r -- 4 John users 1024 Nov 2 TMP
-RW-r -- 1 John users 2941465 Oct 9 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.
--------------------------------------------------------------------------------
As you can see, the process is clearly divided into several segments: Connection (establish a connection with the FTP server), verification (determine whether the user has the right to enter the system), transmission (including the column directory, upload or download files), cancel the connection.

Procedure of using PHP for FTP
Follow these steps to create an FTP connection for PHP: open a connection-send authentication information-Use PHP functions to manipulate directories and transfer files.
Specific implementation:
--------------------------------------------------------------------------------
<?

// Connect to the FTP server
$ Conn = ftp_connect ("ftp.server.com ");

// Use username and password to log on
Ftp_login ($ Conn, "John", "doe ");

// Obtain the remote system type
Ftp_cmdype ($ conn );

// List objects
$ Filelist = ftp_nlist ($ Conn ,".");

// Download an object
Ftp_get ($ Conn, "data.zip", "data.zip", ftp_binary );

// Close the connection
Ftp_quit ($ conn );

?>
--------------------------------------------------------------------------------
Let's step by step:
To complete an FTP connection, PHP provides the ftp_connect () function, which uses the host name and port as the parameter. In the preceding example, the host name is "ftp.server.com". If the port is not specified, PHP uses "21" as the default port to establish a connection.
After the connection is successful, ftp_connect () returns a handle. This handle will be used by subsequent FTP functions.
--------------------------------------------------------------------------------
<?

// Connect to FTP Server
$ Conn = ftp_connect ("ftp.server.com ");

?>
--------------------------------------------------------------------------------
Once a connection is established, use ftp_login () to send a user name and password. As you can see, this function ftp_login () uses handle from the ftp_connect () function to confirm that the user name and password can be submitted to the correct server.
--------------------------------------------------------------------------------
<?

// Log in with username and password
Ftp_login ($ Conn, "John", "doe ");

?>
--------------------------------------------------------------------------------
At this time, you can do what you want to do, specifically in the next section:

After you finish what you want, remember to use the ftp_quit () function to close your FTP connection.

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

// Close connection
Ftp_quit ($ conn );

?>
--------------------------------------------------------------------------------
After logging on to the FTP server, PHP provides some functions that can obtain information about the system, files, and directories.

Ftp_pwd ()
If you want to know your current directory, you need to use this function.
--------------------------------------------------------------------------------
<?

// Get current location
$ Here = ftp_pwd ($ conn );

?>
--------------------------------------------------------------------------------
In case you need to know what system the server is running?
Ftp_systype () is provided to you in this regard.
--------------------------------------------------------------------------------
<?

// Get system type
$ Server_ OS = ftp_cmdype ($ conn );

?>
--------------------------------------------------------------------------------
Regarding the PASV switch, PHP also provides a function that enables or disables PASV (1 indicates on)
--------------------------------------------------------------------------------
<?

// Turn PASV on
Ftp_pasv ($ Conn, 1 );

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

Now, you know where you are and who you are with. Now we are going to browse through the directory-The ftp_chdir () function is used to implement this function, it accepts a directory name as a parameter.
--------------------------------------------------------------------------------
<?

// Change directory to "public_html"
Ftp_chdir ($ Conn, "public_html ");

?>
--------------------------------------------------------------------------------
If you want to return to the directory (parent directory) where you are located, ftp_cdup () can help you achieve your wish. This function can return to the upper-level directory.
--------------------------------------------------------------------------------
<?

// Go up one level in the directory tree
Ftp_cdup ($ conn );

?>
--------------------------------------------------------------------------------
You can also create or move a directory, which uses the ftp_mkdir () and ftp_rmdir () functions. Note: If ftp_mkdir () is successfully created, the new directory name will be returned.
--------------------------------------------------------------------------------
<?

// Make the directory "test"
Ftp_mkdir ($ Conn, "test ");

// Remove the directory "test"
Ftp_rmdir ($ Conn, "test ");

?>
--------------------------------------------------------------------------------
Creating an FTP directory usually involves transferring files-Let's get started!

First, upload the file. The ftp_put () function is competent for this responsibility. It requires you to specify a local file name, the uploaded file name, and the transfer type. For example, if you want to upload the "“abc.txt”" file and the name is" “xyz.txt ", the command should be as follows:
--------------------------------------------------------------------------------
<?

// Upload
Ftp_put ($ Conn, "xyz.txt", "abc.txt", ftp_ascii );

?>
--------------------------------------------------------------------------------
Download file:
The function provided by PHP is ftp_get (). It also requires a file name on the server, the downloaded file name, and the transmission type as the parameter. For example, if the server file is his.zip, download it to the terminal and name it hers.zip. The command is as follows:
--------------------------------------------------------------------------------
<?

// Download
Ftp_get ($ Conn, "hers.zip", "his.zip", ftp_binary );

?>
--------------------------------------------------------------------------------
PHP defines two modes as transmission modes: ftp_binary and ftp_ascii. For more information about the two modes, see this article, for more information, see related books.

How can I list objects? (Using dir? :))
PHP provides two methods: a simple list of file names and directories, and a detailed list of file size, permissions, creation time, and other information.
First, use the ftp_nlist () function, and second, use ftp_rawlist (). both functions require a directory name as the parameter. Both return the directory column as an array, and each element of the array is equivalent to a row in the list.
--------------------------------------------------------------------------------
<?

// Obtain file listing
$ Filelist = ftp_nlist ($ Conn ,".");

?>
--------------------------------------------------------------------------------
You must know the file size! Don't worry, here is a very easy function ftp_size (), which returns the size of the file you specified, using bites as the unit. It should be noted that if it returns "-1", it means that this is a directory. In the following example, you will see the application of this function.
--------------------------------------------------------------------------------
<?

// Obtain file size of file "data.zip"
$ Filelist = ftp_size ($ Conn, "data.zip ");

?>

Now, we have come into contact with a large number of FTP functions in PHP, but this is just a function. It is far from our goal and we need to show the real strength of these functions, we should establish a program that can upload and download files on the web --- this is what we will do!

Before entering the code, I would like to tell you that this example is only intended to explain the use of various FTP functions in PHP, and is not complete in many aspects. For example, error analysis and so on. As for how you want to apply it to your own program, you should make some modifications!

The program includes the following files:
Index.html-Logon File

Actions. php-FTP Code required by the program

Include. php-main program interface, which displays the file list and control buttons.

Let's start with "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>
--------------------------------------------------------------------------------
This is a login form with a server name, user name, and password. Enter a box. The input variables are saved to the $ server, $ username, and $ password variables. After the form is submitted, actions. php is called, which initializes the FTP connection.

Note that "hidden" is a variable $ action passed to action. php and the value is CWD.

This is the source code of the action. php file:
--------------------------------------------------------------------------------
<HTML>
<Head>
<Basefont face = Arial>
</Head>
<Body>

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

<?

// Check the data transmitted from the form. If the data is incomplete, an error is returned. To improve the program, a more comprehensive input detection function should be provided here.
If (! $ Server
! $ Username
! $ Password)
{
Echo "incomplete data submission! ";
}
Else
{
// Keep reading
}

?>

</Body>
</Html>
--------------------------------------------------------------------------------

The following is the variable "actions". The program allows the following actions:

"Action = CWD"

Change working directory

"Action = Delete"

Delete a specified file

"Action = download"

Download a specified file

"Action = upload"

Upload a specified file

If you carefully check the file include. PHP, including an HTML interface, you will see that it includes many forms, each pointing to a specific function, each form contains a field (usually hidden), when the form is submitted, the corresponding function will be executed.

For example, if you press "Delete" and "Action = Delete", the message is sent to "actions. php"

The code in actions. php is as follows:
--------------------------------------------------------------------------------
<?
// Action: Change the Directory
If ($ action = "CWD ")
{
// Code
}

// Action: delete an object
Else if ($ action = "delete ")
{
// Code
}
// Action: download an object
Else if ($ action = "Download ")
{
// Code
}
// Action: upload a file
Else if ($ action = "Upload ")
{
// Code
}

?>
--------------------------------------------------------------------------------
The specific code above will implement the specified function and exit the loop. They all include the following steps:

--------------------------------------------------------------------------------
Connect to and log on to the FTP server through custom functions
Connect ();

Turn to the appropriate directory

Execute the selected Function

Refresh the list to view the changed results

Use include ("include. php") to display the file list and control buttons

Close connection
--------------------------------------------------------------------------------
Note:
The following functions support multi-file operations-"Action = Delete" and "Action = download", which are implemented using the for loop.
Variables $ cdir and $ here are updated in real time at each stage.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.