Tuesday, August 18, 2009

Doing FTP in PHP

I had an issue during a development of one of my projects. One of the modules deals with FTP'ing files from one server to another. My script was able to login with no issues but I wondered why it was not able to write or ftp_put anything. I googled for few hours finding out how to overcome this issue that I have and came over with these links...

http://www.php.net/manual/en/function.ftp-pasv.php
http://us.php.net/manual/en/function.ftp-put.php#73168

Both of these links tell that you have to use ftp_pasv to set the ftp connection in passive mode. Meaning the ftp connection will be initiated from the client instead from the server. Also take note that ftp_pasv should be done immediately after calling the ftp_login.

Here is the comment I read there which gave or shed me the light for succesfully getting around with my problem.

"If you are having timeouts uploading a file, even very small files, you might have a look at ftp_pasv()

And don't forget to do it after your ftp_login();"

The sample code below shows how to do it.

$file = 'somefile.txt';
$remote_file = 'readme.txt';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// turn passive mode on
ftp_pasv($conn_id, true);

// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
echo
"successfully uploaded $file\n";
} else {
echo
"There was a problem while uploading $file\n";
}

// close the connection
ftp_close($conn_id);
?>

I hope this experience that I had and I shared with you will help you out fixing issues doing FTP in PHP. Thanks, Cheers and God Bless!!!!

No comments: