Download via FTP

New Articles

On Jabber.

PHP File upload progres bar.

The case of the missing errors.

Retrieving files with FTP and raw sockets

You know by now that you need to set up a data connection using the PASV or PORT commands before you can upload or download a file. Once you make the connection all you have to do is just send the RETR command with the path to the file to be retrieved.

Since ours is a web based FTP client we will not save the retrieved file to disk. If we tried to do so, it will be saved on the webserver, which isn't very usefull for the end user. We need to pass the filethrough to the browser so that the user can save it own his own computer.

The first step is accomplished with this code:

 	function retr($path)
			$this->sock_write("RETR $path");
				return $this->data_sock;
		return "";

As you see the retr() method merely returns a file handle, insted of actually saving the file. Our FTP class is really usefull only if we abstracted the RFC959 functionality from the presentation. Such separation leaves the door open to using our FTP class as to build command line FTP clients or other web clients with a completely different user interface.

The next bit of code shows you how to 'pass through' the file to the browser and cause a file->save as dialog to pop up.

$sock = $ftp->retr(trim($filename));
		$mime_type = (strstr($HTTP_USER_AGENT,'IE') ||
			? 'application/octetstream'
			: 'application/octet-stream';

		// finally send the headers and the file
		header('Content-Type: ' . $mime_type);
		header('Expires: ' . $now);

		if (strstr($HTTP_USER_AGENT,'IE')) {
			header('Content-Disposition: inline; filename="' . $filename. '"');
			header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
			header('Pragma: public');
		} else {
			header('Content-Disposition: attachment; filename=". 
					$filename .'"');
			header('Pragma: no-cache');

	echo 'file could not be retrieved';

Those headers don't look at all like bed time reading but you can give it a try by downloading the FTP class and the file retrieval script, let's move on to the next page where we will see the script in action. Logo

FTP Applet

  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