Transfer Files Via FTP in PHP

      No Comments on Transfer Files Via FTP in PHP

Here is a simple php snippet to upload files from the local server to a remote location:

$file = 'source_file_pathname';
$remote_file = 'destination_file_name';
$conn_id = ftp_connect('');
$login_result = ftp_login($conn_id, 'username', 'password');
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) 
	echo "File successfully uploaded to server.
"; } else { echo "Problem encountered when uploading the file to server
"; } ftp_close($conn_id);

Some hosting providers disable the option to use php ftp functions. However there is an alternative solution to upload files via ftp from php using the fopen/fwrite functions:

$dest = fopen("" . 'destination_file_name', "wb");

$buffer = file_get_contents('source_file_pathname');
fwrite($dest, $buffer, strlen($buffer));


If the files are to big to be buffered all at once in memory, they can be copied on chunks in a loop, reading buffers of a specific size.

A third option if the first 2 can not be used would be to use curl from php:

$ch = curl_init();
$fp = fopen('source_file_pathname', 'r');
curl_setopt($ch, CURLOPT_URL, '' . 'destination_file_name');
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize('source_file_pathname'));
curl_exec ($ch);
$error_no = curl_errno($ch);
curl_close ($ch);
if ($error_no == 0) {
	echo 'File uploaded successfully via FTP.';
} else {
	$error = 'Some error occurred while uploading file';

Leave a Reply

Your email address will not be published. Required fields are marked *