PHP FTP/SFTP Function

Sharing the two powerful PHP file transfer function using FTP and SFTP.

FTP
{code type=php}
function ftpUpload($ftp_host, $ftp_username, $ftp_password, $ftp_path, $filename) {

//Connect to FTP host
if (!$ftp = ftp_connect($ftp_host)) {
die (‘Unable to connect to the specified FTP.’);
}

//Login to FTP
if (!$ftp, $ftp_username, $ftp_password)) {
die (‘Unable to login to the FTP Server.’);
}

//local file name destination or new filename
$local_filename = $filename;

//Upload file to ftp host.
if (!ftp_put($ftp, $filename, $local_filename, FTP_ASCII)) {
die(‘Unable to upload file.’);
}

return TRUE;

}
{/code}


SFTP
{code type=php}
function sftpUpload($ftp_host, $ftp_username, $ftp_password, $ftp_path, $filename) {

if (! function_exists(‘ssh2_connect’)) {
die(‘function is not available.’);
}

//Connect to SFTP host
$connection = ssh2_connect($loc_ftp_host, $port=22);
if (! $connection)
die(‘Could not connect to $ftp_host on port $port.’);

//Login to SFTP host
if (! ssh2_auth_password($connection, $loc_ftp_username, $loc_ftp_password))
die(‘Could not authenticate with username and password.’);

$sftp = ssh2_sftp($connection);

if (! $sftp) die(‘Could not initialize sftp subsystem.’);

//Create or open file
$stream = fopen(‘ssh2.sftp://’.$sftp.$ftp_path.’/’.$filename, ‘w’);

if (! $stream) die(‘Could not open file: $filename’);

$local_filename = $filename;

$data_to_send = file_get_contents($local_filename);

if ($data_to_send === false)
die(‘Could not open local file: $local_filename.’);

if (@fwrite($stream, $data_to_send) === false)
die(‘Could not send data from file: $local_filename.’);

@fclose($stream);

return TRUE;

}
{/code}


Reference:
FTP Manual – http://php.net/manual/en/book.ftp.php
SFTP Manual – http://www.php.net/manual/en/ref.ssh2.php

Advertisement

3 Responses to “PHP FTP/SFTP Function”

  1. 03-22-11 at 11:36 am #

    Good Post, thanks for sharing it with us.

  2. 04-12-11 at 6:57 pm #

    trying to find you on facebook, wats ur profile

  3. Aris Royo
    04-13-11 at 8:33 pm #

    add me aris royo or visit my domain arisroyo.com :)

Leave a Comment