Passive Mode FTP

New Articles

On Jabber.

PHP File upload progres bar.

The case of the missing errors.

FTP :: Passive mode data transfer

After you login, the first thing you see with most FTP clients is a directory listing. We will try to add that functionality to our code in this step. However first we need to build some infrastructure.

Before you retrieve any data from the server you need to establish second connection to it. Our short and sweet guide to the File Transfer Protocol tells you more about this. You can choose between a passive connection and an active connection.

We will only use passive mode for data transfers. That's because it's much easier with PHP and less likely to be hindered by firewalls. When you send the PASV command the server might respond with something similar to the following:


> 227 Entering Passive Mode (127,0,0,1,54,255)

The above response tells us which IP and port number we should establish our Data connection on. The code sample below will process this information and establish the connection.

  
  function pasv()
  {
	$this->sock_write("PASV");
	if($this->is_ok())
	{
		$offset = strpos($this->message,"(");

		$s = substr($this->message,++$offset,strlen($this->messsage)-2);
		$parts = split(",",trim($s));
		$data_host = "$parts[0].$parts[1].$parts[2].$parts[3]";
		$data_port = ((int)$parts[4] data_sock = fsockopen($data_host,$data_port,&$errno,&$errstr,30);
		return $this->data_sock;
	}
	
  }
  

In most cases the IP address returned by the server for the PASV command will match the IP address that you established your 'control connection' on. However according to the RFC it can be different. Thus it is technically possible for you to open a Control Connection on server A and a Data Connection on Server B and transfer files directly from server A to B. Unfortunately this feature is often disabled.

When you download the complete script you will see that the code from the previous page has been improved by turning it into a PHP class. We will refine it further at the next step


SourceForge.net Logo

FTP Applet

Navigation
  Part 1   Introduction ,   Data Connection ,   Directory List ,   demo
  Part 2   Architecture ,   Downloading ,   Demo ,   Sessions
  Part 3   CWD ,   CDUP ,   Where am I? ,   Prune and Graft
  Part 4   Upload ,   Rename ,   Delete,   No operation