Click here to Skip to main content
15,898,035 members
Articles / Programming Languages / PHP
Tip/Trick

FTP Management Script in PHP

Rate me:
Please Sign up or sign in to vote.
4.67/5 (2 votes)
25 Aug 2013MIT4 min read 10.1K   2   2  
How to create a FTP manager application to connect your server to FTP server

Introduction

I would like to introduce PHP functions to connect your server to FTP server. I have created an application using PHP functions do it. I have shared this application file on some websites before.

Advantages

I would like to inform you about its advantages because you will think what's the use of this PHP script when there are highly advanced applications like "FILEZILLA" available.
It has its own uses:

  • It allows to connect your server to FTP server
  • You don't want an intermediate computer to upload a file from FTP server to your server

Background

This idea of FTP client using PHP originated when I wanted to upload a file to my server. It is not good when I download the file to my computer and upload it to my server.
From here came the idea of making an FTP client that will help to connect server to FTP server.

Using the Code

Let's check how the application is implemented in PHP.
First of all, I want a storage medium to store the host, username and password of FTP Server. It is not good when using:

PHP
$user   = $_GET['usrname'];
$passwd = $_GET['passwrd'];
$host	 = $_GET['host'];

I want to store the value of the variables in a medium. So I selected session cookies to store the value of variables for later use. Now the code will look like this:

PHP
$user = $_COOKIE['ftpuser'];
$passwd = !$_COOKIE['ftppassword']?"":$_COOKIE['ftppassword'];
$host = $_COOKIE['host'];

So when the user fills the form and submits it, I will store the values of forms like this:

PHP
if(isset($_GET['host']) && isset($_GET['usrname']) && isset($_GET['passwrd']))
{
	global $user, $passwd, $host;
	setcookie("ftpuser", $_GET['usrname']);
	setcookie("ftppassword", $_GET['passwrd']);
	setcookie("host", $_GET['host']);	
}

Now let us check the FTP function of PHP which will help to connect FTP Server. To connect a FTP server use, $connect = ftp_connect($host);
It will try to connect to FTP Server. The function ftp_connect will return a boolean value to $connect. Now if it is successful, the next step is to login to FTP Server. To login to FTP Server, use function ftp_login. So the code will become $login = ftp_login($connect, $user, $passwd);
The function ftp_login will return a boolean value to $login
Later now the next step is to read the files in FTP Server. The are two functions to do a listing of files in FTP server - ftp_nlist and ftp_rawlist. So here, ftp_rawlist is advanced type of directory listing because it will return almost every details of files in FTP Server.

PHP
function dirDetails($directory=".")
{
	global $connect;
	if(is_array($directs=ftp_rawlist($connect, $directory)))
	{
		$prop = array();
		$nl=count($directs);
		foreach($directs as $dirx)
		{
			$chunks = preg_split("/[\s]+/", $dirx, 9);
			list($prop['perm'], $prop['num'], $prop['user'], $prop['group'], 
			$prop['size'], $prop['mon'], $prop['day'], $prop['time']) = $chunks;
			$prop['type']=$chunks[0]{0}==='d'?'Directory':'File';
			$prop['name']=$chunks[8];
			array_splice($chunks, 0, 8);
			$props[implode(" ", $chunks)]=$prop;
		}
		return $props;
	}
}

The function dirDetails() will read files in directory when we call the function with path as parameter (current working directory '.' as default).
The inner function will split the output from ftp_rawlist according to permission, user, group, size(in bits), last modified date(month, day, time), type of file and name of file.
To show the details of files and directories in the FTP Server, the following function is used:

PHP
$property = dirDetails($fpath);
foreach($property as $prop)
{
	global $fpath;
	$modified = date("F d Y",ftp_mdtm($connect, $prop['name']));
	if($prop['type']=='Directory')
	{
		print "<tr><td><a href='?fpath=".$fpath."/".$prop["name"]."
		'>[ ".$prop["name"]." ]</a></td><td>".$prop['type']."
		</td><td>".filesizex($prop['size'])."</td><td>$modified
		</td><td><a href='?fpath=$fpath&chperm=".$prop['name']."
		'>".$prop['perm']."</a></td><td>".$prop['user']."
		</td><td>".$prop['group']."</td><td>
		<a href='?fpath=$fpath&rename=".$prop['name']."'>Rename</a> | 
		<a href='?fpath=$fpath&deleteDir=".$prop['name']."'>
		Delete</a></td></tr>";
	}
	else
	{
		print "<tr><td><a href='?fpath=$fpath&
		fopen=".$prop['name']."'>".$prop['name']."</a></td><td>
		".$prop['type']."</td><td>".filesizex($prop['size']).
		"</td><td>$modified</td><td><a href='?fpath=$fpath&
		chperm=".$prop['name']."'>".$prop['perm']."</a></td><td>
		".$prop['user']."</td><td>".$prop['group']."</td><td>
		<a href='?fpath=$fpath&fopen=".$prop['name']."'>Download</a> | 
		<a href='?fpath=$fpath&rename=".$prop['name']."'>Rename</a> | 
		<a href='?fpath=$fpath&delete=".$prop['name']."'>Delete</a>
		</td></tr>";
	}
}

To download a file from FTP Server $down = ftp_get($resource, $fname, $fname, FTP_ASCII); here $resource is connection stream, first $fname represents in what name the file downloads, second $fname represents the remote file and the third parameter FTP_ASCII represents resumepos of download.

PHP
function download($resource, $fname)
{
	$down = ftp_get($resource, $fname, $fname, FTP_ASCII);
	if($down)
	{
		success("The file ".$fname." downloaded successfully");
	}
	else
	{
		failed("The file ".$fname." failed to download");
	}
}

The above snippet is the exact function I used. To delete a file from FTP Server, you can use function ftp_delete($connect, $file);

PHP
function deleteFiled($file, $dire)
{
	global $connect;
	ftp_chdir($connect, $dire);
	$del = ftp_delete($connect, $file);
	if($del)
	{
		success("The file $file deleted successfully");
	}
	else {
		failed("The file $file cannot delete");
	}
}

The above snippet is used by me to delete the file.

To delete a directory, you can simply call the function ftp_rmdir($connect, $file);
But it will fail to execute if the directory is not empty. So before deleting the directory, you should delete all files and directories from the desired directory. You can use a recursive function to do it.

PHP
function deleteDir($file, $cdir)
{
	global $connect, $fpath;
	$arraay = dirDetails("$fpath/$file");
	ftp_rmdir($connect, $file);
	foreach ($arraay as $key)
	{
		if($key['type']!='Directory')
		{
			deleteFiledd($fpath."/".$file."/".$key['name']);
		}
		else
		{
			deleteDir($fpath."/".$file."/".$key['name']);
		}
	}
	if(ftp_rmdir($connect, $file))
	{
		success("The directory $file has deleted successfully");
	}
	else 
	{
		failed("The directory $file cannot delete");
	}
}

The function deleteDir() will delete a directory successfully if deletion of directory is set to user.
To upload a file from server to FTP server, the PHP function ftp_put($connect, $file, $file, FTP_ASCII); will help. The first $file represents name of remote file you like to give and second $file represents the current name of file in server.
The exact function I used in the application is:

PHP
function uploadf()
{
	$file=$_GET['upload'];
	global $connect, $host;
	$uploadd = ftp_put($connect, $file, $file, FTP_ASCII);
	if($uploadd)
	{
		success("Successfully uploaded file $file to FTP Server $host");
	}
	else 
	{
		failed("Failed to upload file $file to FTP Server $host");
	}
}

Now we have uploaded, downloaded and deleted from server. Now we want to maintain files in server. I would like to show how to rename a file in server, the PHP function to rename a file is ftp_rename($resource, $fname, $nfname);
The $fname represent the current name of file and $nfname represents a new name for file. The exact function I used is as follows:

PHP
function renamef($resource, $fname, $nfname)
{
	$ren = ftp_rename($resource, $fname, $nfname);
	if($ren)
	{
		success("The file ".$fname." renamed successfully");
	}
	else
	{
		failed("The file ".$fname." failed to rename");
	}
}

Next is to change permission of file in FTP Server. The PHP function to change permission is ftp_chmod($connect, $mode, $file);
You can use function like this ftp_chmod($connect, 0777, "ajithkp.jpg"); to change permission of file "ajithkp.jpg" to mode 777.
The exact code I used is:

PHP
function changeperm()
{
	global $connect, $fpath;
	ftp_chdir($connect, $fpath);
	$mode = $_GET['new_perm'];
	$file = $_GET['fname'];
	$mode = octdec(str_pad($mode, 4, '0', STR_PAD_LEFT));
	if(ftp_chmod($connect, $mode, $file) != FALSE)
		{
			success("The file $file permission changed successfully");
		}
		else 
		{
			failed("The file $file permission cannot changed");
		}
}

The other functions I used in this application are below.
To convert bit size to KB, MB and GB, I used the following function:

PHP
function filesizex($size)
{
    if ($size>=1073741824)$size = round(($size/1073741824) ,2)." GB";
    elseif ($size>=1048576)$size = round(($size/1048576),2)." MB";
    elseif ($size>=1024)$size = round(($size/1024),2)." KB";
    else $size .= " B";
    return $size;
}

To logout from current session, you need to delete the session cookies stored in your browser. To delete cookies I used PHP function setcookie("ftpuser", "");
The exact function I used is:

PHP
function logout()
{
	setcookie("ftpuser", "");
	setcookie("ftppassword", "");
	setcookie("host", "");
}

To change the current directory:

PHP
ftp_chdir($connect, $fpath);

To get FTP system type:

PHP
ftp_systype($connect);

To get current timeout:

PHP
ftp_get_option($connect, FTP_TIMEOUT_SEC)

I hope you enjoyed this tip and the application.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Systems Engineer Tata Consultancy Service Ltd.
India India
Name Ajith Kp. Currently working at Tata Consultancy Service Ltd. I completed MCA from School of Information Science and Techonolgy, Kannur University Campus, Mangattuparamba. I like programming as well as computer/network security analyzing. I'm concentrating programming in Android, PHP, Python, Ajax, JQuery, C# and JAVA.

Blog: http://www.terminalcoders.blogspot.com

Knowledge in Java, Python, PHP, and Android.

Comments and Discussions

 
-- There are no messages in this forum --