jump to navigation

FTP Connection Using PHP January 8, 2011

Posted by Tournas Dimitrios in PHP.

Sending/Receiving files to a server via FTP is an essential ability of any web developer or designer. Of course, we all use glossy FTP clients like WS_FTP and FireFTP, but what about FTP automation? You can use PHP to FTP files from one server to another. Let me show you how :

Please don’t forget that FTP is an unsecure protocol and should not be used for transferring critical files . The Linux users already know that ,  and use SSH or SCP instead . My blog has published many tutorials related to the SSH protocol , just find them 🙂

First example : This sample code shows you how to connect to a remote FTP server using PHP’s built-in functions, retrieve a text file and save it on the current server.

 $FtpCon = ftp_connect("www.someurl.com");
 $FtpLog = ftp_login($FtpCon, "Username", "Password");

      if ((!$FtpCon) || (!$FtpLog)) {
 echo "FTP connection failed.";
      }else {

 echo "FTP connection successful.";

 $LocFile = fopen("SaveTo.txt","w");

 $RemFile = ftp_fget($FtpCon, $LocFile, "SaveFrom.txt", FTP_BINARY);

      if (!$RemFile){

 echo "Could not obtain file.";

      } else {

 echo "File retrieved successfully!";



Second example : Sending files to the FTP server .Although a different implementation  , the concept remains the same. Once the connection is created, you pass the login credentials. Once you’re logged in, you can use the ftp_put() function to send the file. That’s it!

$connection = ftp_connect($server);

$login = ftp_login($connection, $ftp_user_name, $ftp_user_pass);

if (!$connection || !$login) { die('Connection attempt failed!'); }

$upload = ftp_put($connection, $dest, $source, $mode);

if (!$upload) { echo 'FTP upload failed!'; }


See the FTP manual : >>>>>



No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s