PHP Connection and File Handling on FTP Server

Handling file on the server is a very common task for developers. There are many file manager software are available. But without using this software, we can handle file management on the server using PHP. PHP provides lots of functions to handle FTP connection.

In this article, we are using the following FTP functions to manage files on the server -

  • ftp_connect - Connect to FTP connection.
  • ftp_login - Login to FTP Server.
  • file_exists - Check existence of file.
  • filemtime - Last file modification time.
  • ftp_mdtm - Unix timestamp of last file modification time.
  • fopen - Open the file.
  • ftp_fget - Download the file from FTP server.
  • ftp_quit - Close an FTP connection.
  • fclose - Close an open file.

Here is the simple example to connect and handle file on the FTP Server.

	<title>PHP Connection & File Handling on FTP Server</title>
$host = 'hostname';
$user = 'ftp username';
$password = 'ftp password';
$remotefile = 'remotefilename';
$localfile = 'localfilename';
// Connect to host
$conn = ftp_connect($host);
if(!$conn) {
	echo 'Error: could not connect to ftp server';

echo 'Connected to '.$host.'<br/>';

$result = ftp_login($conn, $user, $password);
	echo "Error: could not log on as ".$user; 
echo "logged in as ".$user;

// Check file
echo "Checking file time";
	$localtime = filemtime($localfile);
	echo 'Local file last updated';
	echo date('G:i j-M-Y', $localtime);
	echo '<br/>';
else {
	$localtime = 0;
	$remotetime = ftp_mdtm($conn, $remotefile);
	if(!($remotetime >= 0)) {
		echo "Cann't accesss remote file time";
		$remotetime = $localtime + 1;
	else {
		echo 'Remote file last updated';
		echo date('G:i j-M-Y', $remotetime);
		echo '<br/>';
	if(!($remotetime > $localtime)){
		echo 'Local copy is uptodate';
	echo 'Getting file from server';
	$fp = fopen($localfile, 'w');
	if(!$success = ftp_fget($conn, $fp, $remotefile, FTP_BINARY)){
		echo 'Could not download file';
	echo 'file downloaded successfully';
	//close connection

Read more articles

General Knowledge

Learn Popular Language