Oct 12, 2011

PHP & FTP

You can put files on the server through ftp.


Before we begin with the tutorial, you may want to download my PHP FTP class. This class is a simple wrapper around the native PHP FTP functions.
Most of the PHP applications store and read their settings from a configuration file. Normally an installer script is used to write the settings to the config file and then an admin section is provided through which the administrator can manage these settings. Normal PHP file functions like fopen and fputs can be used to create and write to the configuration file.
But there is a major drawback with this approach. If you want to create a file/directory through a PHP script in another directory, say, includes, then the directory includes need to be writable by the PHP script. Most of the times this means that you will need to chmod the directory to 777. This is a big security hole.
Another problem is that, more often than not, the owner/group of the newly created file is set to that of the PHP process. PHP process normally run as “nobody” or “www”. This means that the newly created file will be owned by “nobody” or “www” and you might not be able to delete the file through FTP. You will have to delete the file through a PHP script.
A simple workaround to the above problems would be to use the chmod and chown functions. Unfortunately both these functions don’t work on most shared hosting plans.
//Make the file writable by all
chmod('somefile',0777);

//Open the file and write to it
$fp = fopen('somefile', 'w');
fputs($fp,$data); fclose($fp);

//Make the file writable only by the owner
chmod('somefile',0644);
Therefore we will use PHP’s FTP functions to create files, directories and to change the mode of files. The functions that are of importance to use here are: ftp_mkdirftp_put and ftp_site.

Connecting to FTP server

Use ftp_connect function to connect to FTP server and use ftp_login function to login to FTP server.
//Connect to the FTP server
$ftpstream = @ftp_connect('localhost');

//Login to the FTP server
$login = @ftp_login($ftpstream, 'user', 'secret');
if($login) {
 //We are now connected to FTP server.
}

//Close FTP connection
ftp_close($ftpstream);
You can read whole tutorial here.