SFTP File Upload with PHP

Quick PHP code snippet to upload a file to a remote server using SFTP.

This code will connect and upload a file to the server. It does not have proper error handling and there are more than likely more efficient ways to load the file, especially large files.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
 
$server = 'ftp.example.com';
$port = '22';
$username = 'bob';
$passwd = 'mysecurepassword';
 
// connect
$connection = ssh2_connect($server, $port);
if (ssh2_auth_password($connection, $username, $passwd)) {
// initialize sftp
$sftp = ssh2_sftp($connection);
 
// Upload file
echo "Connection successful, uploading file now..."."n";
 
$file = 'test.txt';
$contents = file_get_contents($file);
file_put_contents("ssh2.sftp://{$sftp}/{$file}", $contents);
 
} else {
echo "Unable to authenticate with server"."n";
}

Leave a Reply

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