Uploading files with SFTP

To upload files using SFTP (Secure File Transfer Protocol) in PHP, you can use the SSH2 extension, which allows you to connect to an SFTP server and perform various operations such as uploading, downloading, and deleting files. Here is an example of how you can use the SSH2 extension to upload a file to an SFTP server:

<?php
$connection = ssh2_connect('example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
$file = '/path/to/local/file.txt';
$remote_file = '/path/to/remote/file.txt';
ssh2_scp_send($connection, $file, $remote_file, 0644);
?>

This example first establishes a connection to the SFTP server using the ssh2_connect function, and then authenticates with a username and password using the ssh2_auth_password function. Next, it opens an SFTP session using the ssh2_sftp function and then uses the ssh2_scp_send function to upload the file.

Watch a course Learn object oriented PHP

Alternatively, you can use other libraries like phpseclib, which provides an SFTP implementation in pure PHP.

<?php
include 'Net/SFTP.php';

$sftp = new Net_SFTP('example.com');
if (!$sftp->login('username', 'password')) {
  exit('Login Failed');
}

$local_file = '/path/to/local/file.txt';
$remote_file = '/path/to/remote/file.txt';
$sftp->put($remote_file, $local_file, NET_SFTP_LOCAL_FILE);
?>

Please note that these are just examples and actual implementation might change depending on your requirements.