Using FTP in PHP scripts

Using FTP in PHP scripts: Part II

The previous page we looked at basic usage of FTP inside PHP scripts. This covered connecting to an FTP server, listing files, uploading files and downloading files. In this article we will examine advanced FTP features in PHP.

Resuming an FTP download

FTP resumption is a lifesaver to people who regularly move files over the Internet. It works like this: a user is downloading a file from an FTP site. The server, the Internet connection or something else fails. When the user tries to retrieve the file again, the FTP client is in a position to realise that a file by that name has already been downloaded (at least partially). The FTP client can verify whether the files are the same size. If the local file is smaller, the user is asked whether they want to treat the file as a download resumption or download the full file. If the user chooses to resume, the FTP client sends an offset of the number of bytes from the beginning of the file at which to start.

PHP also provides this functionality to developers. This means that you can add fault tolerance and increased efficiency to your FTP-enabled PHP scripts.

Consider the following:

<?
$FILE = "test.txt";
$size = file_exists($FILE) ? filesize($FILE) - 1 : 0;
/* ... */
$remsize = ftp_size($conn,$FILE);
if($remsize == $size + 1) {
echo "Remote file is the same size as local file\n";
} else if($remsize > $size + 1) {
if(!ftp_get($conn,$FILE,$FILE,FTP_ASCII,$size)) {
echo "Could not download $FILE\n";
}
}
/* ... */
?>

This snippet of code tests whether a local file, $FILE, is the same size as a remote file. If it is the same size, the user is informed. If the remote file is larger than the local file, the script retrieves it. The third line of the script determines the size of the $FILE locally. If $FILE exists, filesize() returns the size in bytes. The script reduces the size returned by 1 byte, since the resumption functionality counts from zero, not one.

If the file does not exist, the script sets the file size to zero bytes.

The example skips over the code involved in connecting and authenticating with an FTP server.

Finally, the script gets the file size of the remote file and compares it to $size. If the two files are equal in size, the user is notified. If the remote file is larger, the script resumes the download at offset $size.

Non-blocking FTP

With the FTP functions we've looked at so far, when a script downloads or uploads a file, the script blocks - that is, it stops executing until the download or upload finishes. Non-blocking code is the opposite: the code continues to execute and the user can test whether or not the network function has finished when convenient. This is very useful if, say, your script has to do things unrelated to an FTP transfer. Those things can be done in parallel to the download. Consider the following:

<?
$FILE = "test.txt";
/* ... */
ftp_nb_get($conn,$FILE,$FILE,FTP_BINARY);
/* ... */
while(($ret = ftp_nb_continue($conn)) == FTP_MOREDATA) {
sleep(1);
}
if($ret == FTP_FINISHED) {
echo "Finished downloading $FILE\n";
} else {
echo "An error was encountered downloading $FILE\n";
}
?>

This script uses ftp_nb_get() to initiate the FTP download. It accepts the same arguments as ftp_get(). However, the function does not block the script - it allows it to execute code in parallel with the download. To check on the status of the download, the script calls ftp_nb_continue().

This returns one of three values: FTP_MOREDATA - there is more data to download; FTP_FINISHED - the download is complete; or, FTP_FAILED - an error was encountered. To force the script to block, we loop while ftp_nb_continue() returns FTP_MOREDATA, sleeping for one second for each iteration.

Finally, when the script breaks out of this loop, the final return value of ftp_nb_continue() is tested to see if the file was downloaded or if an error was encountered.

More information on FTP-related functions can be found at www.php.net/manual/en/ref.ftp.php.

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® Professional 1800x microSDHC™/microSDXC™ UHS-II cards 

Learn more >

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

Learn more >

Lexar® JumpDrive® C20c USB Type-C flash drive 

Learn more >

Audio-Technica ATH-ANC70 Noise Cancelling Headphones

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?