Using FTP in PHP scripts

The File Transfer Protocol (FTP) is widely used to transfer files across networks. Utilising it in a PHP script allows you to increase the level of sophistication of your PHP scripts as well as learn more about how FTP works. Before proceeding, get the details of an FTP account to which you have read and write access. For example, most Internet service providers give users an account on their Web servers to host a small amount of data, to which access is generally provided via FTP.

Python vs. PHP: Choosing your next project's language

Alternatively, if you have your own UNIX or Linux system, you should already have an FTP server.

Installation

The FTP extension needs no additional libraries to make it work, but you must recompile PHP. To include FTP support, run the following in the PHP source directory:

./configure --enable-ftp [other options]

The --enable-ftp argument configures FTP support to be added. If you want to include support for other extensions, such as PostgreSQL, be sure to specify their respective arguments to the configure script. Then it is just a matter of compiling and installing the FTP-enabled version of PHP. For more information on this process, see the INSTALL file in the PHP source directory.

A basic FTP session

A basic FTP session involves connecting to an FTP server, logging in with a username and password, interacting with the server and closing the connection. The following script can be used to do this:

01 <?
02 $HOST="somehost.com.au";
03 $UN="username";
04 $PW="password";
05 $DIR="/remote/directory/";
06 $FILE="test.txt";
07
08 $conn = ftp_connect($HOST);
09 if(!$conn) {
10 exit("Could not connect to server: $HOST\n");
11 }
12
13 if(!ftp_login($conn,$UN,$PW)) {
14 ftp_quit($conn);
15 exit("Could not log in\n");
16 }
17
18 ftp_chdir($conn,$DIR);
19
20 $files = ftp_nlist($conn,".");
21
22 for($i=0;$i<count($files);$i++) {
23 if(!ftp_get($conn,$files[$i],$files[$i],FTP_ASCII)) {
24 echo "Could not download {$files[$i]}\n";
25 }
26 }
27
28 if(!ftp_put($conn,$DIR.$FILE,$FILE,FTP_ASCII)) {
29 echo "Could not upload $FILE\n";
30 }
31
32 ftp_quit($conn);
33 ?>

Lines 02 through 06 define some parameters that will be specific to your setup. Set $HOST to an FTP server to which you have access; set $UN and $PW to the username and password, respectively, for the server; set $DIR to a directory on the remote server to which you have read and write access; and set $FILE to a local file you want to upload to the remote server.

On line 08, the script attempts to connect to $HOST - if it cannot, it fails out. On line 13, the script sends the username and password information required to authenticate access with the server. If the username and/or password are incorrect - or if there is an error - we exit from the script, informing the user. The script also tidies up after itself, closing the FTP session using ftp_quit().

If all goes well, on line 18 the script changes to the remote directory $DIR. On line 20, we retrieve a list of files in $DIR using the ftp_nlist() function. This function returns an array of files names. On lines 22 through 26, the script loops through the files, retrieving each (line 23) using ftp_get(). The second argument to ftp_get() specifies the local filename to which the remote file will be downloaded. The third argument specifies the remote file in which we are interested.

Finally, the fourth argument is the mode in which to download the file. There are two modes: FTP_ASCII for ASCII or text files; and FTP_BINARY for files in binary format, such as images or executables. Generally speaking, the mode that is chosen only matters if the client, server or both are not UNIX systems. The script uses FTP_ASCII. If any error is encountered when trying to download a file, the script notifies the user. On line 28, the script attempts to upload $FILE to the remote server using ftp_put(). The second argument specifies the remote file name, while the third specifies the local filename. As with ftp_get(), the fourth argument is the mode in which to transfer the file. If an error is encountered, the script tells the user.

The FTP session is closed on line 32 using ftp_quit().

Join the PC World newsletter!

Error: Please check your email address.

Our Back to Business guide highlights the best products for you to boost your productivity at home, on the road, at the office, or in the classroom.

Keep up with the latest tech news, reviews and previews by subscribing to the Good Gear Guide newsletter.

Gavin Sherry

PC World
Show Comments

Essentials

Lexar® JumpDrive® S57 USB 3.0 flash drive

Learn more >

Microsoft L5V-00027 Sculpt Ergonomic Keyboard Desktop

Learn more >

Mobile

Lexar® JumpDrive® S45 USB 3.0 flash drive 

Learn more >

Exec

Lexar® JumpDrive® C20c USB Type-C flash drive 

Learn more >

Audio-Technica ATH-ANC70 Noise Cancelling Headphones

Learn more >

Lexar® Professional 1800x microSDHC™/microSDXC™ UHS-II cards 

Learn more >

HD Pan/Tilt Wi-Fi Camera with Night Vision NC450

Learn more >

Budget

Back To Business Guide

Click for more ›

Most Popular Reviews

Latest News Articles

Resources

PCW Evaluation Team

Azadeh Williams

HP OfficeJet Pro 8730

A smarter way to print for busy small business owners, combining speedy printing with scanning and copying, making it easier to produce high quality documents and images at a touch of a button.

Andrew Grant

HP OfficeJet Pro 8730

I've had a multifunction printer in the office going on 10 years now. It was a neat bit of kit back in the day -- print, copy, scan, fax -- when printing over WiFi felt a bit like magic. It’s seen better days though and an upgrade’s well overdue. This HP OfficeJet Pro 8730 looks like it ticks all the same boxes: print, copy, scan, and fax. (Really? Does anyone fax anything any more? I guess it's good to know the facility’s there, just in case.) Printing over WiFi is more-or- less standard these days.

Ed Dawson

HP OfficeJet Pro 8730

As a freelance writer who is always on the go, I like my technology to be both efficient and effective so I can do my job well. The HP OfficeJet Pro 8730 Inkjet Printer ticks all the boxes in terms of form factor, performance and user interface.

Michael Hargreaves

Windows 10 for Business / Dell XPS 13

I’d happily recommend this touchscreen laptop and Windows 10 as a great way to get serious work done at a desk or on the road.

Aysha Strobbe

Windows 10 / HP Spectre x360

Ultimately, I think the Windows 10 environment is excellent for me as it caters for so many different uses. The inclusion of the Xbox app is also great for when you need some downtime too!

Mark Escubio

Windows 10 / Lenovo Yoga 910

For me, the Xbox Play Anywhere is a great new feature as it allows you to play your current Xbox games with higher resolutions and better graphics without forking out extra cash for another copy. Although available titles are still scarce, but I’m sure it will grow in time.

Featured Content

Latest Jobs

Don’t have an account? Sign up here

Don't have an account? Sign up now

Forgot password?