13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Backing Up or Mirroring a File<br />

465<br />

This function takes two parameters—the FTP connection h<strong>and</strong>le <strong>and</strong> the path to the<br />

remote file—<strong>and</strong> returns either the Unix timestamp of the time the file was last modified<br />

or –1 if there is an error of some kind. Not all FTP servers support this feature, so<br />

you might not get a useful result from the function. In this case, you can choose to artificially<br />

set the $remotetime variable to be “newer” than the $localtime variable by<br />

adding 1 to it.This way, you ensure that an attempt is made to download the file:<br />

if (!($remotetime >= 0))<br />

{<br />

// This doesn’t mean the file’s not there, server may not support mod time<br />

echo ‘Can’t access remote file time.’;<br />

$remotetime=$localtime+1; // make sure of an update<br />

}<br />

else<br />

{<br />

echo ‘Remote file last updated ‘;<br />

echo date(‘G:i j-M-Y’, $remotetime);<br />

echo ‘’;<br />

}<br />

When you have both times, you can compare them to see whether you need to download<br />

the file:<br />

if (!($remotetime > $localtime))<br />

{<br />

echo ‘Local copy is up to date.’;<br />

exit;<br />

}<br />

Downloading the File<br />

At this stage, you try to download the file from the server:<br />

echo ‘Getting file from server...’;<br />

$fp = fopen ($localfile, ‘w’);<br />

if (!$success = ftp_fget($conn, $fp, $remotefile, FTP_BINARY))<br />

{<br />

echo ‘Error: Could not download file’;<br />

fclose($fp);<br />

ftp_quit($conn);<br />

exit;<br />

}<br />

fclose($fp);<br />

echo ‘File downloaded successfully’;<br />

You open a local file by using fopen(), as you learned previously. After you have done<br />

this, you call the function ftp_fget(), which attempts to download the file <strong>and</strong> store it<br />

in a local file.This function takes four parameters.The first three are straightforward: the

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!