PHP FTP/SFTP Function

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

FTP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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;

}



SFTP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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;

}



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