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.

<html>
<head>
	<title>PHP Connection & File Handling on FTP Server</title>
</head>
<body>
<?php
$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';
	exit;
}

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

$result = ftp_login($conn, $user, $password);
if(!$result){
	echo "Error: could not log on as ".$user; 
	ftp_quit($conn);
	exit;
}
echo "logged in as ".$user;

// Check file
echo "Checking file time";
if(file_exists($localfile)){
	$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';
		exit;
	}
	echo 'Getting file from server';
	$fp = fopen($localfile, 'w');
	
	if(!$success = ftp_fget($conn, $fp, $remotefile, FTP_BINARY)){
		echo 'Could not download file';
		ftp_quit($conn);
		exit;
	}
	fclose($fp);
	echo 'file downloaded successfully';
		
	//close connection
	ftp_quit($conn);
}
?>
</body>
</html>




Read more articles


General Knowledge



Learn Popular Language